How to sort the result of wp_query

I am trying to sort the results of wp_query, I want to sort it by different parameters without making the query again. I have something like this:

$the_query = new WP_Query( $args );

      

And I want to sort $ the_query, WP_Query returns structure like this:

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

      

So, I want, for example, to sort all items by name. I've tried this:

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

      

I want to sort after the request is done. This is because I want to sort many times and I donโ€™t want to query every time I want to sort

DECISION

This returns a fatal error: You cannot use an object of type WP_Post as an array

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

      

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

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

      

so you need to change $a['title'] - $b['title']

for $a->title - $b->title

and using Peter Gusen's answer, the end result is:

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

      

thanks for all

+3


source to share


2 answers


Look at the parameters orderby

and order

in WP_Query

. If you need to sort by post title, you can add the following 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 
            );
});

      

+5


source


WP_Query ('orderby = date & order = DESC')

Or try it if you want to sort based on custom meta value.



$args = array(
        'post_type' => 'post',
        'meta_key' => 'pb_issue_featured',
        'orderby'   => 'meta_value',
        'order' => 'DESC',
        'posts_per_page' => $posts,
        'paged' => $paged,
        'paged' => 1,
        'meta_query' => array(
            array(
                'key' => 'headline',
                'value' => 1,
                'compare' => '!=' 
                )
            )
        );

add_filter( 'posts_orderby', 'filter_query' );
$q = new WP_Query($args);
remove_filter( 'posts_orderby', 'filter_query' );

function filter_query( $query ) {
    $query .= ', wp_posts.menu_order ASC';
    return $query;
}

      

0


source







All Articles