C. Max
C. Max

Reputation: 75

WordPress how to use multiple meta_query and meta_key

I'm using a meta_query with a relation 'OR' with two keys to retrieve all tags and it working perfectly

$args = array(
    'taxonomy'   => 'post_tag',
    'hide_empty' => true,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'   => 'key-check',
            'value' => false,
        ),
        array(
            'key'     => 'key-check',
            'compare' => 'NOT EXISTS',
        ),
    ),
);

I have to add another different key but I don't know-how is the best way to do it. I thought to use the below code and add another meta_query but it's correct or I'm making an error?

$args = array(
    'taxonomy'   => 'post_tag',
    'hide_empty' => true,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'   => 'key-check',
            'value' => false,
        ),
        array(
            'key'     => 'key-check',
            'compare' => 'NOT EXISTS',
        ),
    ),
    'meta_query' => array(
        array(
            'key'   => 'another-key',
            'value' => true,
        ),
    ),
);

Upvotes: 1

Views: 8926

Answers (2)

Nishan Mozumder
Nishan Mozumder

Reputation: 21

You can use multiple meta query & skip empty values:

$arg = [
    'post_type'     => 'post',
    'status'        => ['publish'],
    'post_per_page' => -1,
];

$arg['meta_query'] = [
    'relation' => 'OR',
    [
        'key' => 'custom_1',
        'value' => '',
        'compare' => '!='
    ],
    [
        'key' => 'custom_2',
        'value' => '',
        'compare' => '!='
    ],
];

Upvotes: 2

Bhautik
Bhautik

Reputation: 11282

You are using the same "meta_query" key twice that's why the issue is creating. check the below code.

$args = array(
    'taxonomy'   => 'post_tag',
    'hide_empty' => true,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'   => 'key-check',
            'value' => false,
        ),
        array(
            'key'     => 'key-check',
            'compare' => 'NOT EXISTS',
        ),
        array(
            'key'   => 'another-key',
            'value' => true,
        ),
    ),
);

Upvotes: 2

Related Questions