最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

customization - Add to search posts query array with post IDS which will appear first

matteradmin9PV0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0

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
  usort($wp_query->posts,'sortByIds');

  //then your normal code....
}

It is not an sql solution but it works.

Post a comment

comment list (0)

  1. No comments so far