0

I want to order a query result by the same order as the post id's array given. E.g. I have:

$arrayPostsIds = array(30,5,17,10);

and I want to get the posts in that order. So after trying this:

add_filter('posts_orderby', 'edit_posts_orderby');

function edit_posts_join_paged($join_paged_statement) {
    global $arrayPostsIds_id;
    $join_paged_statement = 'FIELD(ID,'.implode(',',$arrayPostsIds).')';
    return $join_paged_statement;   
}

and then I get the new result, which should match the above order:

$temp = $wp_query; // assign ordinal query to temp variable for later use  
$wp_query = null;
$wp_query = new WP_Query( array( 'post__in' => $arrayPostsIds, 'ignore_sticky_posts' => true, 'date_query' => $date_query ) ); 

but I'm getting the result ordered by ID, so it's not keeping the desired order. Am I forgetting anything?

1 Answer 1

1

Remove your filter and add orderby'=>'post__in'. That sort order in not automatic when you supply IDs.

$wp_query = new WP_Query( 
  array(
     'post__in' => $arrayPostsIds,
     'ignore_sticky_posts' => true, 
     'date_query' => $date_query ,
    'orderby' => 'post__in',
  ) 
);
3
  • I had also tried this, but I'm getting the same result.
    – Manolo
    Mar 22, 2014 at 19:30
  • If $arrayPostsIds is set correctly this should work. You will need to remove your filter.
    – s_ha_dum
    Mar 22, 2014 at 19:31
  • Oh man! It works just removing the filter! Thank you for your fast answer.
    – Manolo
    Mar 22, 2014 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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