phpfilteringmeta-key

How to order by multiple meta keys with WP_Query?


I’m trying to order with two custom key in a custom post type.

$args = array(
    'post_type' => 'my_new_post_type',
    'meta_query' => array(
        'relation' => 'AND',
        'firstArray_clause' => array(
            'key' => 'my_first_key',
            'value' => 'My first value',
            'compare' => 'EXISTS',
        ),
        'secondArray_clause' => array(
            'key' => 'my_second_key',
            'compare' => 'EXISTS',
        ), 
    ),
    'orderby' => array(
        'firstArray_clause' => 'ASC',
    ),
);
$MyQuery = new WP_Query( $args);

So for "my_first_key" I just want it to exist and I want to order by the value of "my_second_key".


Solution

  • I found the solution:

    $MyQuery = new WP_Query( array(
        'post_type'     => 'my_new_post_type',
        'meta_query' => array(
            array(
                'key'     => 'my_first_key',
                'value'   =>  "My first value",
                'compare' => 'LIKE',
            ),
        ),
        'meta_key'       => 'my_second_key',
        'orderby'       => 'meta_value_num',
        'order'          => 'ASC',
    ) );
    

    I don't know if I'm understandable with the names of my values but you can change my_first_key to 'category' and my_second_key to 'order'.