a post has the following custom fields:
'my_custom_field' => 1
'my_custom_field' => 2
'my_custom_field' => 3
I now want to query all posts that do NOT contain the value 2 for ‘my_custom_field’. I’m trying this:
$args = Array('posts_per_page' => -1,
'post_type' => 'page',
'meta_query' => array(
array(
'key' => 'my_custom_field',
'value' => 2,
'compare' => '!='
)
)
);
However, this is still returning my sample post, as my sample post has a field of ‘my_custom_field’ with a value other than 2 (1 and 3). I somehow need to change my query to say “Exclude posts that have at least one field of ‘my_custom_field’ with the value of 2”.
Can anyone help me? Thanks!
This might require writing custom sql with a subquery:
then just iterate through the results as described here.
As @TomJNowell and @s_ha_dum says you in comments, in your case probably a custom taxonomy is better than custom fields, because is very easy to get a post that has not a taxonomy term.
That said, I understand that if you have a lot of code alreadt wrote, or you are working with third party code, moving to custom taxonomy can be hard / not possible.
Aswer provided by @elleeott works, however is not flexible, because you can’t change posts per page, meta value, etc..
I’ll provide you a similar solution, but a bit more flexible and you can fine tune it to fit your needs.
Essentially is just a class that extend
WP_Query
and apply filters to request to perform a what you wantAfter that, instead of using
WP_Query
you have to useMyMetaQuery
class:Note thats the only params the custom class accepts are:
'post_type'
, can be a single types, a comma-separed string or anarray of types or ‘any’
'post_status'
can be a single status, a comma-separed string or anarray of statuses or ‘any’
'posts_per_page'
can be a posistive number or ‘-1’'nopaging'
can beTRUE
orFALSE
. Set to TRUE will return all posts overriding ‘posts_per_page’'meta_query'
accepts a multidimensional array, just likeWP_Query
. Note that you can only pass one query array, any additional query will be ignored. The query array accepts as array keys:'key'
,'value'
and'compare'
.'value'
can be a single value, a comma-separed string or an array of values.'compare'
can be ‘IN’, ‘NOT IN’, ‘=’ and ‘!=’If you need other arguments (category, tags, taxonomies, date, etc) you must extend the class features or, more probably, use another approach.