When you want to get some WordPress posts, products, custom posts, whatever, you usually head straight to the wp_query loop. If you want to show, say, a set of products chosen from dropdown selects in the back end by a user, you might end up with something like this:

  $args = array(
      'post_type'     => 'product',
      'post_status'   => 'publish',
      'post__in'      =>  array($prod1,$prod2,$prod3,$prod4),
  );
  
  $products = new WP_Query( $args );

where “array($prod1,$prod2,$prod3,$prod4)” is an array of 4 product ids from the select boxes.

But when you render that query on the front end, the products come out seemingly randomly out of order. Product 1 is where 3 should be, number 4 is in first position and product 2 is last . That’s because an SQL database gives you results in an order determined by what it sees to be the most efficient execution plan for the query.

What if you wanted them in the original order of the array? You need to tell the database that by using an ORDER BY clause.

In WordPress you can order by title, author, date and lots more, but one handy one you might not know about is the ‘post__in’ parameter. This will order the data in the order of the array passed to ‘post__in’.

The full code:

  $args = array(
      'post_type'     => 'product',
      'post_status'   => 'publish',
      'post__in'      =>  array($prod1,$prod2,$prod3,$prod4),
      'orderby'       => 'post__in',
  );
  
  $products = new WP_Query( $args );

Now your products will be displayed in the original order they are in the array! Yay!

Order wp_query by the order of your input array

Leave a Reply

Your email address will not be published.