Query Posts in a Predefined Order

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

Leave a Comment