Order posts by ID in the given order

In the back-office of my theme, the users can choose which posts to display in the front page, and they can also choose in which order the selected posts should appear.

I have tried like this:

Read More
$aPostsIDs = array(1,3,2); // Note the 3 should appear before the 2
query_posts(array('post_type' => 'page', 
                  'post__in' => $aPostsIDs,
                  'order_by' => 'FIELD(ID, '.implode(',',$aPostsIDs).')'));

But as expected it doesn’t work. The right way to do it according to the codex is:

add_filter('posts_orderby', 'edit_posts_orderby');
function edit_posts_orderby($orderby_statement) {
    global $aPostsIDs;
    $orderby_statement = 'FIELD(ID, '.implode(',',$aPostsIDs).')';
    return $orderby_statement;
}

But that still doesn’t work! The posts are ordered by ID (1, 2, 3) instead of the given order (1, 3, 2).

Where should I look?
Thanks

Related posts

Leave a Reply

1 comment

  1. Starting in WordPress 3.5, the orderby parameter will allow the value post__in to sort by the order of the post__in parameter, just like in your example.

    It may not be ideal to wait or require 3.5+, but this will almost certainly be the best and easiest way to do what you’re looking to do.

    Here’s the relevant trac ticket if you want the details.