How to Exclude a Post or Page from WordPress Search Results

I needed to have one post in a site I’m building not appear in search results. I came across this handy bit of code that totally does the trick, and it works for a page, too:

/** Exclude from search */
function mySearchFilter($query) {
if ($query->is_search) {
$excludeId = 199;
$query->set('post__not_in', array($excludeId));
}
return $query;
}
add_filter('pre_get_posts','mySearchFilter');

Copy and paste the above code in your theme’s Functions file:

Dashboard > Appearance > Themes > Editor > Functions.php

Then, replace “199” in this example with the ID of the page or post you want excluded. To find the ID, edit the page or post in the dashboard and look for this number:

postnumber

You might need to access the Functions.php file in your themes folder via FTP if you have a custom install.

This right here is one of the main reasons I love WordPress. Because it’s open source and so widely-adopted, chances are there’s a solution for whatever basic issue may arise. To find this result I just Googled, “How to exclude page in WordPress search” and was taken to this support discussion from several years ago. Even though it’s from a previous decade, the advice still worked, and I hope it might help you also.

What do you think? Have you ever been led to WordPress forums via Google search for a how-to type of question? How do you prefer to find answers to these issues? Let us hear from you in the comments.

Leave a Reply