I want to exclude every post with a specific value of a custom meta field.
The problem is, that not every posts has this meta field.
My code looks like this (excerpt of the working loop):
// WP_Query arguments
$args = array (
'post_parent' => $parentid,
'orderby' => 'menu_order',
'order' => 'ASC',
'post_type' => array( 'page' ),
'meta_query' => array(
array(
'key' => 'hide',
'value' => 1,
'compare' => '!='
)
)
);
Not every posts uses the field “hide”. Some posts giving back a NULL.
So I think, the loop isn’t working because of that?!
Is this correct? Is it necessary that every posts has a value for that key?
Another way to do it:
This is an old post, but to answer it anyways. The meta query in this question will only return results of posts that have that meta key. To also return posts that do not have that meta key at all, you need an additional meta query. Example:
Note the use of “relation” and the second meta query which has the compare value of ‘NOT EXISTS’.
UPDATE WITH HOW I HANDLE THIS SITUATION PRESENTLY:
I seem to run into situations like this more and more, and I’ve developed a method for handling it which results in a much quicker SQL query. Whenever a post in the post type in question is saved, I update a list of post IDs that meet my query criteria and store it in a WP option. Then when my query is run, I get this list, and either put it in the ‘include’ or ‘exclude’ query parameter depending on if this is a whitelist or a blacklist.
This does add a bit of code but the benefits here are both in performance, and also removing some complexity if you have other meta queries that also need to run. Some example code below for a blacklist, this could be adapted for a whitelist as well.
Then in a query for posts:
Try to check your SQL Statement by doing like below snippet.