WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

FROM wp_posts
    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?

share|improve this question

closed as off-topic by toscho Dec 28 '13 at 17:04

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

I don't think post__in is an accepted parameter for orderby. – helgatheviking Aug 1 '13 at 9:56
Yes it apparently is so, as of WP 3.5. I’m running 3.5.2. Check codex.wordpress.org/Class_Reference/… – Max Aug 1 '13 at 10:16
You're correct. That's news to me. – helgatheviking Aug 1 '13 at 13:14

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' 
share|improve this answer

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.

share|improve this answer

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