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.


1 Answer 1


It 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

  //then your normal code....

It is not an sql solution but it works.

  • Thanks! 1. I'm getting the search via the rest api with &search=search term. 2. What if the post ids are not at all in the search results, I still need them to be on top, and remove the bottom posts to not have more then posts_per_page. and paged 2 should not be losing these posts, so it has to be something build in
    – BenB
    Commented Oct 24, 2018 at 13:47
  • Could you show us your code please so that it will be easier to help you.
    – Friss
    Commented Oct 24, 2018 at 13:48
  • example.com/wp-json/wp/v2/posts?search=car&per_page=12&page=1 This will search "car" in posts and return 12 posts via the default wp search function
    – BenB
    Commented Oct 24, 2018 at 15:49
  • How is it handle in your template file?
    – Friss
    Commented Oct 24, 2018 at 19:33
  • It's a headless WordPress setup, no template files only rest api calls frond end with vue.js/react
    – BenB
    Commented Oct 24, 2018 at 20:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.