0

I'd like to make a query of custom posts based on a custom field, say instrument. I need to be able to query only those posts for which the custom field has not been set (i.e. for which the meta value does not exist). Is there a way to achieve this with meta_query ? Here's the code for the query :

$args = array(
    'post_type' => 'my_custom_post_type',
    'nopaging' => true
);

$args['meta_query'] = array(
                            array(
                                'key'       => 'instrument',
                                // when value is not even set.
                            )
                        );

}

$the_query = new WP_Query( $args );

2 Answers 2

2

As documented, you can set the compare property of the meta query to NOT EXISTS:

$args['meta_query'] = array(
    array(
        'key'     => 'instrument',
        'compare' => 'NOT EXISTS',
    ),
);
0
2

The meta query can take an argument called "compare" which can be set to "NOT EXISTS".

So your meta query should look like this:

$args['meta_query'] = array(
    array(
        'key'       => 'instrument',
        'compare'   => 'NOT EXISTS'
    )
);

The list of all arguments for the meta_query can be found in the codex: https://codex.wordpress.org/Class_Reference/WP_Meta_Query

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.