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.

1
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.

Leave a Comment