WP_Query order by multiple meta keys & fields

How to order query by multiple meta keys and fields/custom fields?

This is my code:

$args = array
    (
        'post_type' => 'listing',
        'posts_per_page' => -1,
        'tax_query' => array
        (
            array
            (
                'taxonomy' => 'listing_category',
                'field' => 'slug',
                'terms' => urldecode($category)
            ),
            array
            (
                'taxonomy' => 'location',
                'field' => 'slug',
                'terms' => urldecode($location)
            )
        ),

        //*** THIS NOT WORK
        'meta_query'    => array
        (
            array(
                'key'     => 'listing_status',
                'orderby' => 'meta_value',
                'order' => ASC,
            ),
            array(
                'key'     => 'listing_total_rank',
                'orderby' => 'meta_value',
                'order' => DESC,
            ),
            array(
                'key'     => 'listing_free_date',
                'orderby' => 'meta_value',
                'order' => ASC,
            ),
            array(
                'key'     => 'title',
                'orderby' => 'meta_value',
                'order' => ASC,
            ),
        ),
        //***
    );

$listings = new WP_Query( $args );

The part of 'meta_query' does not working in the code.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You are using meta query without setting a value. The way you are doing it is using to query posts, not to order them.

Using Named Meta Queries

To order your posts by different meta datas, you can give your meta queries a name and then use that to set the ordering. Here is a simple example for you:

$args = array(
    'meta_query' => array(
        'relation' => 'AND',
        'query_one' => array(
            'key' => 'key_one',
            'value' => 'value_one', // Optional
        ),
        'query_two' => array(
            'key' => 'key_two',
            'compare' => 'EXISTS', // Optional
        ), 
    ),
    'orderby' => array( 
        'query_one' => 'ASC',
        'query_two' => 'DESC',
    ),
);

You can check this section of codex page for WP_Query() to familiarize yourself with sorting the posts.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x