Sort Query by post_in Parameter WordPress

Allows post queries to sort the results by the order specified in the post__in parameter. Just set the orderby parameter to post__in!

60223_size_n_shape_sorting_board_01_a_109

add_filter( 'posts_orderby', 'sort_query_by_post_in', 10, 2 );
function sort_query_by_post_in( $sortby, $thequery ) {
     if ( !empty($thequery->query['post__in']) && isset($thequery->query['orderby']) && $thequery->query['orderby'] == 'post__in' )
         $sortby = "find_in_set(ID, '" . implode( ',', $thequery->query['post__in'] ) . "')";
     return $sortby;
}

Usage :

$args = array(
     'post_type' => 'post',
     'post__in' => array(10,25,16,8,15),
     'posts_per_page' => 4,
     'orderby' => 'post__in'
 );
 query_posts($args); 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s