WP_Query with an array of IDs order by array WP_Query with an array of IDs order by array wordpress wordpress

WP_Query with an array of IDs order by array


In Wordpress 3.5 and up you can use 'orderby'=>'post__in' then you must write this:

$myarray = $ids;    $args = array('post__in'=> $myarray, 'orderby'=>'post__in');// The Query$the_query = new WP_Query( $args );


I know, that my answer is too late, but i have to answer correctly.

As i tried 'orderby'=>'post__in':

for example i have dynamically updated cookies, and i must to load products in recently viewed products block in order, that first product in this block must be last viewed.

OK.

I had ids 1720, 19626, 19173, 19188.

$args = array('post__in'=> $myarray, 'orderby'=>'post__in');

This string in output returned my products in order:

19626, 19188, 19173, 1720 and its not my order. This cause simply order parameter DESC by default WP_Query. And we have only one another chance - ASC it...very sad answer by M H.

My answer is simply clever:

we DO NOT NEED to 'orderby'=>'post__in'

we have to get:

$myarray = $ids;    $args = array('post__in'=> $myarray);$the_query = new WP_Query( $args );

After it we do:

foreach($myarray as $myarray_id){ while ( $the_query->have_posts()) {   $the_query->the_post();   if($post->ID == $myarray_id){     //DO SOMETHING   } }}

That's it!


Properly transmitting the order:

$id_array = array(5,2,3,7);foreach($id_array as $id_array_v){   $query = new WP_Query(array('post__in' => array($id_array_v)));   while($query -> have_posts())   {      $query -> the_post();      the_title();   }}