11

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:

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?

4
  • I don't think post__in is an accepted parameter for orderby. Commented Aug 1, 2013 at 9:56
  • 3
    Yes it apparently is so, as of WP 3.5. I’m running 3.5.2. Check codex.wordpress.org/Class_Reference/…
    – Max
    Commented Aug 1, 2013 at 10:16
  • 1
    You're correct. That's news to me. Commented Aug 1, 2013 at 13:14
  • Off-topic maybe, but Google leads here, and I was previously unaware of 'orderby' => 'post__in' so +1.
    – DomQ
    Commented Apr 11, 2018 at 12:40

2 Answers 2

43

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' 
);
1
  • 1
    You have no idea how much relief this answer gave me.
    – Mark
    Commented Apr 24, 2019 at 3:33
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.