WP_query ‘orderby=none’ Problem

The question:

I have another database which stores post’s IDs and I want do display them using WP_query to use the WP default pagination. I’m using orderby => none to preserve the original order, but the result reorders them by IDs.

$ids = array (60, 23, 78, 46, 105, 130)

$args = array (
    'posts_per_page' => -1,
    'post__in' => $ids,
    'orderby' => 'none'
);

$query = new WP_Query ( $args );

while ( have_posts() ) : the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

Could anyone help me?

Thanks,
Romulo De Lazzari

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You can order them manually after the query is complete:

$ids = array (60, 23, 78, 46, 105, 130)

$args = array (
    'posts_per_page' => -1,
    'post__in' => $ids,
    'orderby' => 'none'
);

$query = new WP_Query ( $args );

$ordered_posts = array();
foreach($ids as $rpid)
 foreach($query->posts as $index => $fpid)
   if($fpid->ID === $rpid) $ordered_posts[] = $query->posts[$index];

$query->posts = $ordered_posts;

while ($query->have_posts() ) : $query->the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

And like Mamaduka posted, if it’s a custom loop use the $query methods instead of the global functions…

Method 2

Try following snippet:

$ids = array (60, 23, 78, 46, 105, 130)

$args = array (
    'posts_per_page' => -1,
    'post__in' => $ids,
    'orderby' => 'none'
);

$query = new WP_Query ( $args );

while ( $query->have_posts() ) : $query->the_post();
    echo '<li>';
    the_title();
    echo '</li>';
endwhile;

Method 3

orderby none simply uses the order MySQL returns without explicitly ordering by a field, which is typically going to be in order of ID, since that’s how MySQL uniquely identifies each post and how it is able to most efficiently retrieve them from the database.

If you want your custom order, you’ll have to loop through your array of IDs and match them against the returned posts.

Method 4

A better way to use post__in for an order which is you have entered same order list managed in a post.

More info

$ids = array (60, 23, 78, 46, 105, 130)

$args = array (
    'posts_per_page' => -1,
    'post__in' => $ids,
    'orderby' => 'post__in', 
    'order' => 'ASC', 
);

$query = new WP_Query ( $args );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment