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 );
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 );
Share
Improve this question
asked Sep 18, 2019 at 12:57
GuitarExtendedGuitarExtended
2392 silver badges10 bronze badges
2 Answers
Reset to default 2As documented, you can set the compare
property of the meta query to NOT EXISTS
:
$args['meta_query'] = array(
array(
'key' => 'instrument',
'compare' => 'NOT EXISTS',
),
);
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/Class_Reference/WP_Meta_Query