Meta query with multiple logic (AND / OR)

I realise this has been asked before, but this feature seems to have been added in v4.1 and the accepted answers aren’t helpful (they’re pre-4.1).

How can I “chain” meta queries with ANDs and ORs? I’ve found this Update on Query improvements in 4.1 but I can’t seem to get the syntax correct for my application.

I’d like to query posts where flagged is not 1 AND (expiry_date is in the future OR blank)

I’ve tried re-ordering the arrays and ‘relations’ without effect (there are definitely posts in the database which match this query).

The date part of the query works fine, but the addition of the flagged query returns no posts.

'meta_query'    => array(
    'relation' => 'AND',
    array( 
        'key'     => 'flagged',
        'value'   => '1',
        'compare' => '!='
    ),
    array(
        'relation' => 'OR',
        array(
            'key'       => 'expiry_date',
            'value'     => date('Y-m-d',strtotime("today")),
            'compare'   => '>=',
            'type'      => 'DATETIME',
        ),
        array( //has no date
            'key'       => 'expiry_date',
            'value'     => '',
            'compare'   => '='
        )
    )
)

1 Answer
1

The correct syntax for performing the AND OR is as follows:

'meta_query'    => array(
    'relation' => 'AND',
    array( 
        'key'     => 'flagged',
        'value'   => '1',
        'compare' => '!='
    ),
    array(
        'relation' => 'OR',
        array(
            'key'       => 'expiry_date',
            'value'     => date('Y-m-d',strtotime("today")),
            'compare'   => '>=',
            'type'      => 'DATETIME',
        ),
        array( //has no date
            'key'       => 'expiry_date',
            'value'     => '',
            'compare'   => '='
        )
    )
)

As a side note, it seems that post meta which are set to NULL (eg flagged) will not be returned by this query. Setting to any other value (such as 0) resolves this issue.

Leave a Comment