I am already filtering some custom posts depending on a querystring in pre_get_posts:

if( $query->is_main_query() ) {
    if( is_post_type_archive( 'events' ) ) {
        if ($_GET['status']) {
            $retrieved_status = $_GET['status'];
            $query->set('meta_key', 'event_status');
            $query->set('meta_value', $retrieved_status);

I would then also like to sort by a different custom field, but I can't use something like below because it rewrites the meta_key:

$query->set('orderby', 'meta_value');   
$query->set('meta_key', 'event_date');   
$query->set('order', 'DESC');

How could I structure this to get the desired effect? Thanks!

2 Answers 2


Use WP_Query to select any post based on meta key and value. You can also sort posts Ex:

$args = array(
    'post_type'  => 'events',
    'orderby'   => 'meta_value_num', //probably you will need this because the value is date
    'meta_key'  => 'event_date',
    'meta_query' => array(
        'relation'  => 'AND',
            'key'     => 'event_status',
            'value'   => $retrieved_status, 
            'compare' => '=',
            'key' => 'other_key',
            'value'   => 'other_value',
            'type'    => 'numeric', //for example
            'compare' => 'BETWEEN', //for example
$query = new WP_Query( $args );

See Order & Orderby Parameters & for meta_value_num see Custom Field Parameters

  • Thanks, I ended up using meta_query in my pre_get_posts and that has worked.
    – Joe Fawley
    Commented Apr 26, 2017 at 7:28

WP_Query has a case for this called a Meta Query where you can pass as many complex arguments as necessary:

$query = new WP_Query array(
    'meta_query'    => array(
        'relation'  => 'AND',       // OR is the default relation parameter, if this is excluded
            'key'       => 'meta_key_one',
            'value'     => 'meta_value_one',
            'compare'   => '<=',
            'key'       => 'meta_key_two',
            'value'     => 'meta_value_two',
            'compare'   => '<=',
) );

The above says:

    All Posts
    Meta Keys Value One is Less Than or Equal to Passed Value One
    Meta Keys Value Two is Less Than or Equal to Passed Value Two

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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