Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

$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

share|improve this question
    
Ok I have found why my second example wasn't working, it was because the add_filter() call needed to be declared before the call to query_posts()! This is now working as expected: $aSectionsIDs = array(1,3,2); add_filter('posts_orderby', 'edit_posts_orderby'); function edit_posts_orderby($orderby_statement) { global $aSectionsIDs; $orderby_statement = 'FIELD(ID, '.implode(',',$aSectionsIDs).')'; return $orderby_statement; } query_posts(array('post_type' => 'page', 'post__in' => $aSectionsIDs)); If I place the query_posts() call just before a –  Rovb Nov 14 '12 at 23:55
    
This system is really stupid! First I need to wait 8 hours to answer my own question (what if I have figured it out before that delay??), and second it suggests me as an alternative to post my answer as a comment, but the comment is limited in length so I cannot explain the answer in details. And it removed all line breaks, code and text formating... -_- Anyway I didn't have enough chars left to finish my sentence in my previous comment, so here it is: If I place the query_posts() call just before add_filter() call then it just stops working. –  Rovb Nov 14 '12 at 23:58
add comment

1 Answer

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.