所以在@Nicolai发现WP源中的blurb确认我不能在orderby
如果我订购relevance
我不得不走另一条路。然而,只有在我不喜欢分页的情况下,此路径才有效。也许有一种方法可以把它放回去,但我现在正在研究一种不同的解决方案,我不再需要停留在我的问题中的代码上。
所以我保留了修改查询的函数pre_get_posts
并删除了有关post meta/meta查询的任何内容:
function modify_search_results_order( $query ) {
if ( $query->is_main_query() && is_search() && ! is_admin() ) {
$get_expired_events = Event_Helpers::get_expired_event_ids();
$query->query_vars[\'posts_per_page\'] = - 1;
$query->query_vars[\'order\'] = \'DESC\';
$query->query_vars[\'is_search\'] = true;
$query->query_vars[\'post__not_in\'] = $get_expired_events;
$query->query_vars[\'orderby\'] = \'relevance\';
$query->query_vars[\'post_status\'] = \'publish\';
}
return $query;
}
然后在我的搜索模板中,调用一个函数,在
pre_get_posts
要查找优先帖子,请将其从主查询中取消设置,然后将其放回顶部:
//in search.php
$wp_query->posts = Search_Modify_Query::rearrange_search_query_for_priority_relevance( $wp_query->posts );
//in PHP Class
public static function rearrange_search_query_for_priority_relevance( $query ) {
//get prioritized ids
$get_prioritized = self::get_priority_search_post_ids();
$get_results_ids = [];
if ( ! is_array( $get_prioritized ) || ! $get_prioritized ) {
return $query;
}
//save all ids from current search results query
foreach ( $query as $key => $post ) {
$get_results_ids[ $key ] = $post->ID;
}
if ( ! $get_results_ids ) {
return $query;
}
//check if there are priority posts in results
if ( array_intersect( $get_prioritized, $get_results_ids ) ) {
$priority_matches = array_intersect( $get_results_ids, $get_prioritized );
$priority_query = false;
//if there are priority matches, pluck them out to put them on top
if ( $priority_matches ) {
foreach ( $priority_matches as $key => $priority_match ) {
//save these into new array first
$priority_query[ $key ] = $query[ $key ];
//then unset them from main query
unset( $query[ $key ] );
}
if ( $priority_query && is_array( $priority_query ) ) {
//then re-add them on top of main query
return array_merge( $priority_query, $query );
} else {
return $query;
}
}
}
return $query;
}
这很好,但因为我需要所有的结果来与我的“priority post”ID和结果ID进行比较,所以我必须设置
posts_per_page
至-1。因此,尽管它可以工作,除非我找到一种方法来恢复分页或编写自定义内容,否则搜索结果将显示所有搜索结果。php,无论是5还是500。不过,我还是把这段代码放在这里,以防从长远来看对其他人有所帮助。
但对于我的情况,我决定进行两个单独的查询,并且我确认我们不关心是否有重复的。因此,我将只查询与主搜索结果查询上方的搜索词匹配的优先级帖子。