将结果添加到 WordPress 搜索结果中 [英] Add results into WordPress search results
问题描述
我想在 WordPress 搜索结果中添加/注入/附加额外的结果.
I would like to add/inject/append extra results into the WordPress search results.
目前 WordPress 只允许您调整"在其自己的数据库上执行的查询,但不允许您修改(或用 WordPress 行话,过滤)结果数组.
At the moment WordPress only allows you to "adjust" the query that is being executed on its own database, but doesn't allow you to modify (or in WordPress lingo, filter) the results array.
即:如果我在 WordPress 中搜索potato"这个词,所有与该词相关的帖子都会回来.我想将通过其他服务获得的结果包含到 WordPress 结果集中.
I.e: If in WordPress I search for the term 'potato' all posts related to this term come back. I want to include results that I've obtained via a different service into the WordPress results set.
澄清一下,我是从 3rd 方 API 调用中获取结果的.不是来自 WordPress 数据库.
Just to clarify, I'm getting my results from a 3rd party API call. Not from the WordPress database.
有人知道我该怎么做吗?
Does anyone have an idea on how I can do this?
最好这需要在我的 WordPress 插件中发生,而无需更改搜索模板.
Preferably this needs to happen in my WordPress plugin without having to change search templates.
推荐答案
您可以使用 pre_get_posts
添加/编辑您的搜索结果,而无需更改搜索模板.
You can use pre_get_posts
to add/edit your search result without changing things is search template.
排除搜索结果中的页面.可以创建一个动作挂钩,通过仅显示帖子的结果来限制搜索结果.
To exclude pages in your search results. It is possible to create an action hook that limits the search results by showing only results from posts.
以下示例演示了如何执行此操作:
The following example demonstrates how to do that:
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' );
参考:
Exclude_Pages_from_Search_Results
Include_Custom_Post_Types_in_Search_Results
这篇关于将结果添加到 WordPress 搜索结果中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!