Excluding posts (or custom post types) from search results when they meet certain criteria is easy in theory. Just use the pre_get_posts
action to modify the WP_Query
arguments used to get the results. However there are a couple of small pitfalls to watch out for. Below are brief explanations and snippets for excluding posts based on a taxonomy term and a custom meta field value.
Excluding posts by custom meta field
This seems obvious – a meta_query
with a !=
compare statement. However if you stop there, you will only get posts which have the custom meta field you are matching, but not the value. Posts – e.g. different post types – that don’t even have the meta field will be excluded. To work around this we need to add another part to the query that uses the a NOT EXISTS
compare and join them with an OR
relation.
Exclude posts by taxonomy term
Taxonomy terms are slightly easier – but the trick is in the choice of operator
– it has to be NOT IN
rather than NOT EXISTS
or !=
. While they all sound like they would work, only using NOT IN
will allow you to exclude posts that have that term, while including all posts with other terms in the same taxonomy and also posts which do not have that taxonomy at all.
Here’s the full snippet: