WP_Query orderby post__in remains ineffective in the Loop

I’m trying to query a custom array of posts for the homepage, trying to maintain the order given in the array. To a certain degree this works fine, WordPress finds the posts, but in the Loop the order is all mixed up again.

First of all, I’m using the pre_get_posts hook to change the main query on the homepage, which looks something like this:

Read More
if ( is_home() && $query->is_main_query() ) {
    $query->set( 'post_type', array( 'post', 'page', 'product' ) );
    $query->set( 'post__in', array( 103, 14, 127, 115 ) );
    $query->set( 'orderby', 'post__in' );
}

The order on the homepage is all mixed up! It’s neither following the specified array, nor the publish dates (which is the default). Instead, it’s 127, 103, 14, 115.

I var_dumped the global $wp_query on the homepage, just to check what happened, and the SQL it queried was indeed

SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID
FROM wp_posts
WHERE
    1=1 AND wp_posts.ID IN (103,14,127,115)
    AND wp_posts.post_type IN ('post', 'page', 'product')
    AND (wp_posts.post_status = 'publish' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private')
ORDER BY FIELD( wp_posts.ID, 103,14,127,115 )
LIMIT 0, 10

So no problem there! That’s exactly what should happen. The array of posts in $wp_query->posts however, has the wrong order.

You might notice that there’s a custom post type 'product' included in the query. Is that the culprit? Any idea where to look?

Related posts

2 comments

  1. Set orderby to post__in. This preserves post ID order given in the post__in array (available with Version 3.5).

    $args = array (
        'posts_per_page' => -1,
        'post__in' => $ids,
        'orderby' => 'post__in' 
    );
    
  2. Entirely my bad, I had an old function hooked to the_posts that did some sorting of its own. Old code I forgot to remove. Now it’s running just fine.

Comments are closed.