Hack: Exclude a Specific Post From Searches

So there are lots of snippets of code out there for excluding categories or tags from searches. But what if you just want to exclude a specific post or two, and don’t want to create a whole other category or tag to use for that?

Here is some code you can add to your functions.php that looks for a custom field named search_exception and hides that post in searches.

add_filter('pre_get_posts', 'wpfilter_exclude_from_search' );
function wpfilter_exclude_from_search($query) {
    if ($query->is_search()) {
    	$q = $query->get('meta_query');
     	$q = array(array('key'=>'search_exception', 'value'=>'exclude', 'compare'=>'NOT EXISTS'));
        $query->set('meta_query', $q);

    return $query;

I wanted to keep this code as simple as possible. So I’m assuming you don’t already have any special code that is taking custom fields into account. This code will replace that condition and simply look to see the search_exemption exists. It doesn’t care what is in the field, whether it is the stated exclude or something else. So you can use this field as a way to leave a comment on why this page isn’t included.

Leave a Reply

Your email address will not be published. Required fields are marked *