Is there a way to add array of post IDS to set posts to be on top of search results?
Something like adding a param top_post_ids inside the search hool:
$query->set( 'top_post_ids', [45, 78, 94 ] );
If these posts will appear in search results, they should be on top.
Sticky posts would not solve this issue in this case, has to be array of post IDS.
The search is via WordPress Rest Api so I cannot modify the template file where the search is called.
example/wp-json/wp/v2/posts?search=car&per_page=12&page=1
Is there a way to add array of post IDS to set posts to be on top of search results?
Something like adding a param top_post_ids inside the search hool:
$query->set( 'top_post_ids', [45, 78, 94 ] );
If these posts will appear in search results, they should be on top.
Sticky posts would not solve this issue in this case, has to be array of post IDS.
The search is via WordPress Rest Api so I cannot modify the template file where the search is called.
example/wp-json/wp/v2/posts?search=car&per_page=12&page=1
Share
Improve this question
edited Oct 24, 2018 at 20:26
BenB
asked Oct 11, 2018 at 16:31
BenBBenB
80511 silver badges24 bronze badges
1 Answer
Reset to default 0It is not the most elegant solution, but you could sort the results on your search page:
At the top of your page, make the wp_query variable available
global $wp_query;
Later in you code, if there are some results :
if ( have_posts() ) {
//your desired order
$order = array(45, 78, 94);
// a comparison function to sort the post array with your custom one
function sortByIds($a, $b){
global $order;
$a = array_search($a->ID, $order);
$b = array_search($b->ID, $order);
return $a - $b;
}
//we use usort to sort the wp_query post using a comparison function
// note, we could use a closure if your php version supports it
usort($wp_query->posts,'sortByIds');
//then your normal code....
}
It is not an sql solution but it works.