0
votes

I am using foreach and setup_postdata in the loop to display post. The $args sorting is by 'post_in' but the output is showing in default DESC order of Post IDs in SQL.

Here is the output:

Before args

Array ( [0] => 229 [1] => 226 [2] => 228 [3] => 227 [4] => 225 )

After args

Array ( 
  [post_type] => movies
  [post_in] => Array ( 
    [0] => 229 
    [1] => 226 
    [2] => 228 
    [3] => 227 
    [4] => 225 
  ) 
  [orderby] => post_in 
)

Query dump

string(275) "
SELECT SQL_CALC_FOUND_ROWS wpxc_posts.ID 
  FROM wpxc_posts 
 WHERE 1=1 
   AND wpxc_posts.post_type = 'movies' 
   AND (wpxc_posts.post_status = 'publish' 
 OR wpxc_posts.post_status = 'acf-disabled' 
 OR wpxc_posts.post_status = 'private') 
 ORDER 
    BY wpxc_posts.post_date DESC 
 LIMIT 0, 10"

Actual Sequence

229  
228
227
226
225

The code is as below:

<?php
$postidsstring = get_field('post_ids_to_be_included');
$postidsarray = explode(", ",$postidsstring);
echo "Before args <br>";
print_r($postidsarray);
$args = array(
    'post_type'=> 'movies',
    'post_in' => $postidsarray,
    'orderby' => 'post_in'
);
$myposts = get_posts($args);
?><br><?php
echo "After args <br>";
print_r($args);
echo "<br>Query dump<br>";
$query = new WP_Query($args);
var_dump($query->request);
echo "<br> Actual Sequence";
foreach ( $myposts as $post ) : 
global $post;
setup_postdata( $post ); ?>
<li>
<?php echo get_the_ID(); ?>
</li>   
<?php endforeach;
?>

Please suggest how to control the sorting in this case.

1

1 Answers

0
votes

You can see in the query you posted that it's not sorting by the IDs (or even filtering by them), rather by the post_date:

ORDER BY wpxc_posts.post_date DESC

I believe the issue is a double underscore - note that post_in is not in the spec, whereas post__in is.. Try using this instead:

$args = array(
  'post_type'=> 'movies',
  'post__in' => $postidsarray,
  'orderby' => 'post__in'
);