can I orderby one custom field and meta_query another in the same query

Despite meta_key being deprecated, it is still required to get the orderby to work correctly.

First and foremost though, there’s an error with your code, and that’s in using order_by and not orderby (there’s no underscore in the orderby arg).

Give this a shot and see how it works out for you.

$event_query = new WP_Query( array( 
    'post_type'   => 'event',
    'meta_key'    => 'event-month',
    'meta_query'  => array(
        array( 
            'key'     => 'event-month',
            'value'   => date("n"),
            'compare' => '=',
            'type'    => 'NUMERIC'
        )
    ),
    'orderby'    => 'meta_value',
    'order'       => 'asc', 
) );

If you want to add a second meta key, and sort by that key, just ensure that key is inside the meta_key arg, eg.

$event_query = new WP_Query( array( 
    'post_type'   => 'event',
    'meta_key'    => 'some-key',
    'meta_query'  => array(
        array( 
            'key'     => 'some-key',
            'value'   => 'whatever',
            'compare' => '=',
            'type'    => 'NUMERIC'
        ),
        array( 
            'key'     => 'event-month',
            'value'   => date("n"),
            'compare' => '=',
            'type'    => 'NUMERIC'
        )
    ),
    'orderby'    => 'meta_value',
    'order'       => 'asc', 
) );

Odd that you should need meta_key for the sort, but i don’t see the orderby being respected without it, i can see how the query appears inside debug bar‘s queries tab and as far as i can tell meta_key is currently required to get a proper sort on meta_value.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)