WP_Query with an array of identifier orders by array

I have an array of identifiers and I want to receive these WP_Quey () messages

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

Him, Sorting the result by date But I want to sort it by $ myarray elements, and the first result will be the first identifier in $ myarray

+6
source share
2 answers

In Wordpress 3.5 and above, you can use 'orderby'=>'post__in' , then you should write this:

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

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

How I tried 'orderby'=>'post__in' :

for example, I have dynamically updated cookies and I have to upload products to a recently viewed product block so that the first product in this block should be viewed for the last time.

OK

I had identifiers 1720, 19626, 19173, 19188 .

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

This line displays my products in order:

19626, 19188, 19173, 1720 and its not my order. This results in a simple DESC order parameter by default WP_Query . And we have only one chance - ASC is ... a very sad answer M H.

My answer is just smart:

we do not need 'orderby' => 'post__in'

we have to get:

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

After that we do:

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

What is it!

0
source

All Articles