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
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 
            );
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With