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?
Set orderby to
post__in
. This preserves post ID order given in the post__in array (available with Version 3.5).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.