I'm trying to re-order the search results using the pre_get_posts
hook and set the orderby
parameter to relevance. I also want to put priority posts, which is based on post meta _prioritize_s
to be placed first in the results. Then all the posts after will be based on relevance as usual.
Here's the code I've been messing with:
//runs on pre_get_posts
function modify_search_results_order( $query ) {
if ( $query->is_main_query() && is_search() && ! is_admin() ) {
$query->query_vars['order'] = 'DESC';
$query->query_vars['orderby'] = 'relevance';
$query->query_vars['post_status'] = 'publish';
// $query->query_vars['meta_query'] = [
// 'relation' => 'OR',
// array(
// 'key' => '_prioritize_s',
// 'compare' => 'EXISTS'
// ),
// array(
// 'key' => '_prioritize_s',
// 'compare' => 'NOT EXISTS'
// )
// ];
}
return $query;
}
I originally had the orderby
set to meta_value relevance
and it did put the priority posts on top with the meta_query uncommented. However, it doesn't keep the relevance sorting intact for posts afterwards. It seems like the meta query is affecting the overall order.
I have a feeling I might need something custom like a database query instead? Doesn't seem like I'm going to get what I need by just setting the $query->query_vars
. Can anyone help out? Thanks in advance!
UPDATE: Since I haven't figured out how to alter the code I posted above, I'm trying an alternate solution. Let me know if it's the wrong way to go about it. Leaving the above code alone, I can use the found_posts
hook to alter the search results query after my pre_get_posts
function has already done it's magic. However my only issue is the second parameter that should give me the query is only giving me 10 posts when I know the results should be more than that. Why is it limiting it to 10 posts even if I set posts_per_page
to -1
in my pre_get_posts
function?
function modify_search_results_prioritized( $found_posts, $wp_query ) {
if ( is_search() ) {
//this says 10 - why?
error_out($wp_query->query_vars['posts_per_page']);
}
return $found_posts;
}
orderby
asmeta_value relevance
and that didn't work. It's not in the code example but I wrote in my description that I had tried that. Therelevance
isn't meta, it's a WordPressorderby
parameter you can set to sort posts by relevance for search. Hopefully that helps clear some things up. Let me know. Thanks.fields
parameter withids
, so$query->posts
contains an array of ids. The use of thes
parameter makes WordPress handled it like every other search, so each array is ordered by relevance. Merge the arrays, and then use the combined array to set the parameterpost__in
andorderby
withpost__in
. This is obviously untested, but I think it should work.