Sort Query by Post In

Query for a specific set of post IDs, and return them in that same order.

Sort Query by Post In is a very light weight (about 5 lines of code!) plug-in intended for developers executing custom post queries. You’re welcome to include it in your theme and redistribute — just offer us some credit, please!

When constructing a WordPress post query in your theme template files or plug-in, WordPress offers the option to explicitly specify the posts to retrieve using the “post__in” parameter. Unfortunately, the “orderby” parameter does not offer an option that will sort the result by the exact order passed in the post__in parameter. This plug-in adds a “post__in” option for the “orderby” parameter that will order the result by the exact order specified by the the “post__in” parameter.

And don’t worry about the plug-in being deactivated – your post queries with “post__in” value used for the “orderby” will simply gracefully fall back to the default date sorting.

So what’s the use case? Well, many special themes allow the editor to specify the posts they want to show in certain parts of the front end theme. For example, the user may be able to specific “featured post” #1, #2, and #3 for a part of the home page. Without this plug-in, the template would have to execute a distinct post query for each post to ensure they are presented in the order specified as #1, 2, and 3. Now, a developer can execute a query for all the posts in one shot, sorting them by the specified order.

How does it work?

Let’s say you want to retrieve posts 20, 10, and 106, in that order. You can retrieve those posts without this plug-in using the “post__in” parameter with the post query.

query_posts( array( 'post__in' => array(20,10,106) ) );

But they’ll be ordered by date, or one of the others you specify with the “orderby” parameter. This plug-in adds a new “orderby” option that will order the posts by the order they were specified in the “post__in” array! Here’s how to modify the query above to return the posts in the order specified:

query_posts( array( 'post__in' => array(20,10,106), 'orderby' => 'post__in' ) );

This plug-in was originally inspired by code Jake wrote for, a VIP client. All work to convert the code into a plug-in, and all updates since version 1.0, were completed independently by Jake.

  • Rating
  • Requires 3.0+
  • Downloads 2,954
  • Updated 2012-10-20
  1. Hi,
    I just installed your plugin, but something looks strange,
    it only worked when I changed
    in the plugin code

    maybe something changed in the recent wordpress versions

    • Quite possibly! I’ll investigate.

  2. Hey, it’s working great… Thanks for a nice plugin…

  3. I previously wrote some similar functionality using MySQL’s FIELD() function instead of FIND_IN_SET(). I wonder if there’s a performance difference between the two.

Finely crafted websites & tools that make the web better.