7

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
    I would note that this query is going to be quite slow/expensive – Tom J Nowell Aug 28 '17 at 14:56
17

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.