WP_Query with an array of IDs order by array

I have an array of IDs and I want to get that posts by WP_Quey()

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

Its, Sort result by date But I want to sort it by $myarray items and first result would be first ID in $myarray

Answers


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();
   }
}

Need Your Help

Hide tabs in sub pages in Ionic 2

angular typescript ionic-framework ionic2 ionic3

I try to hide tabs on all my subpages in my app.

Spring configuration XML schema: with or without version?

java spring

I am new to Spring. One thing confuses me is that sometimes I see XML configuration files with versioned schemas, yet sometimes with non-versioned ones. For example, sometimes I see something like