我想在 WordPress 搜索结果中添加/注入(inject)/附加额外结果。
目前 WordPress 只允许您“调整”正在其自己的数据库上执行的查询,但不允许您修改(或用 WordPress 术语,过滤)结果数组。
即:如果我在 WordPress 中搜索术语“马铃薯”,所有与该术语相关的帖子都会返回。我想将通过其他服务获得的结果包含到 WordPress 结果集中。
澄清一下,我是从第 3 方 API 调用中获取结果的。不是来自 WordPress 数据库。
有人知道我该怎么做吗?
编辑:最好这需要在我的 WordPress 插件中发生,而不必更改搜索模板。
最佳答案
您可以使用 pre_get_posts
添加/编辑您的搜索结果,而无需更改搜索模板。
排除页面
在搜索结果中排除页面。可以创建一个操作 Hook ,通过仅显示来自帖子的结果来限制搜索结果。
下面的例子演示了如何做到这一点:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
add_action('pre_get_posts','search_filter');
在搜索结果中包含自定义帖子类型
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array( 'post', 'movie' ) );
}
}
}
add_action('pre_get_posts','search_filter');
包括自定义/API 结果
function search_filter() {
if ( is_search() ) {
// Do your API call here
// Save retrieved data in your wordpress
// This will also help to you avoid api call for repeated queries.
$post_id = wp_insert_post( $post, $wp_error ); // wp_insert_post() // Programatically insert queries result into your wordpress database
array_push( $query->api, $post_id );
}
}
add_action('pre_get_posts','search_filter');
function have_posts_override(){
if ( is_search() ) {
global $wp_query;
$api_post = $wp_query->api;
foreach ($api_post as $key) {
// This will enable you to add results you received using API call
// into default search results.
array_push($wp_query->posts, $key);
}
}
}
add_action( 'found_posts', 'have_posts_override' );
引用:
关于php - 将结果添加到 WordPress 搜索结果中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195818/