I am using the query_posts function to list a 10 specific posts which lookup by post id.
I have an array which looks like this..
Array
(
[0] => 17983
[1] => 17932
[2] => 18030
[3] => 18016
[4] => 17972
[5] => 18013
[6] => 18035
[7] => 17959
[8] => 18020
[9] => 18039
)
I would like to query posts showing it in that specific order, however with my code it shows them in a random order of its own.
Here is the argument I use for query posts:
$args = array(
'post_type' => 'post',
'post__in' => $post_ids,
'numberposts' => 10,
);
$post_ids is the array which I have posted above.
How can I alter my code to query the posts and show them in the order of the array?
If the query is only for a small number of posts, then as linked to by Alex you can sort in php. However, this does not scale well.
As suggested by Kovshenin – a better alternative is to use posts_orderby
filter:
$post_ids = array(83,24,106,2283,14);
$args = array(
'post_type' => 'post',
'post__in' => $post_ids,
'numberposts' => 10,
);
//Callback to filter the ORDER BY part of the query
function wpse67823_orderby_post_in($orderby, $query){
global $wpdb;
//Remove it so it doesn't effect future queries
remove_filter(current_filter(), __FUNCTION__);
$post__in = implode(',',$query->get('post__in'));
return "FIELD( {$wpdb->posts}.ID, $post__in )";
}
//Add filter and perform query
add_filter('posts_orderby','wpse67823_orderby_post_in',10,2);
$wpse67823_query = new WP_Query($args);
3.5+
WordPress 3.5 will see an additional value accepted by WP_Query
for orderby
: ‘post__in’. See this trac ticket: http://core.trac.wordpress.org/ticket/13729