On of the important features needed in every WordPress site is the search function. This allows users to search your website with any keyword. However, when someone search your site, WordPress does not exclude pages from the search result. Here’s an example.
In this example, I searched for “contact form”, so the search result page will list any post and page that contains the word “contact”. As you can see, it will also show my Contact page as one of the results, with no excerpt.
Here’s a little snippet to exclude pages from search result:
<?php | |
/** Exclude Page in Search */ | |
function exclude_search_pages($query) { | |
if ($query->is_search) { | |
$query->set('post_type', 'post'); | |
} | |
return $query; | |
} | |
add_filter('pre_get_posts','exclude_search_pages'); |
Please note that this only exclude the pages when someone search on your site. It does block any Google bots from crawling any page.
Vivek R says
I’m wondering how it excludes the page from Search Engine crawlers.
Editor says
If you use any seo plugin like Yoast and AISEO, I’m prettty sure in the seo metabox for every page, there’s an option to set the page to NOINDEX.