Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort the result of wp_query

I'm trying to sort the results of wp_query, i want to sort it by different parameters without make the query again. I have something like that:

$the_query = new WP_Query( $args );

And i want to sort $the_query, WP_Query returns a structure like that:

$the_query->posts[0]->title; 

So, I want to sort all the elements by 'title' for example. I tried this:

usort($the_query->posts, function($a, $b) {
   return $a['title'] - $b['title'];
});

I want to sort after i do the query. Is because i want tosort many times and i dont want to do the query every time i want to sort

SOLUTION

This returns Fatal error: Cannot use object of type WP_Post as array

usort($the_query->posts, function($a, $b) {
   return $a['title'] - $b['title'];
});

This is because the structure of the array is like that:

$the_query->posts[0]->title; 

so you have to change $a['title'] - $b['title'] for $a->title - $b->title and using the answer of Pieter Goosen the Final result is:

usort($the_query->posts, function($a, $b) {
    return strcasecmp( 
            $a->title, 
            $b->title
        );
});

Thank for all

like image 232
Juan M. González R. Avatar asked Nov 15 '14 06:11

Juan M. González R.


1 Answers

Look at the orderby and order parameters in WP_Query. If you need to sort by post title, you can add the following to your query parameters

'orderby' => 'title'
'order' => 'ASC'

EDIT

If you need to sort with usort, you can do the following

usort($the_query->posts, function($a, $b) {
   return strcasecmp( 
                $a->post_title, 
                $b->post_title 
            );
});
like image 92
Pieter Goosen Avatar answered Sep 20 '22 18:09

Pieter Goosen