By default, WordPress search behavior supposes the ability to display all published pages and posts in the search results. When a user is browsing a blog, they are more likely to look for a post rather than for a page. Sometimes website owners want to make their search results more relevant and that is why they want to restrict search results to certain pages or posts in WordPress.
We will talk of two most recognized ones:
The first way is more suitable for experienced users with some coding skills, and the second one is appropriate for almost anyone. If you choose the second variant, then it is up to you whether to select free or premium plugins for your particular needs.
1. So, the first variant supposes working with your functions.php file. This file is a kind of template used by a WordPress theme. This one automatically loads both in admin and front-end pages of your WP website. It is used for defining functions, actions, classes and filters that other templates utilize within a certain theme.
The following code can be added to your functions.php file if you want to restrict the search results to any selected page or post.
//Exclude pages from WordPress Search
if (!is_admin()) {
function wpb_search_filter($query) {
if ($query->is_search) {
$query->set(‘post_type’, ‘post’);
}
return $query;
}
add_filter(‘pre_get_posts’,’wpb_search_filter’);
}
This code will make sure that the search doesn’t come from the WordPress admin pages and then it will search for posts by setting the post_type parameter. You can also set the post_type parameter to pages to make it return the pages in the search results.
2. For the second variant we will use the Search Exclude free WP plugin to fulfill our aim. So go to Plugins -> Add New, find a plugin with the help of the search field, install and activate the plugin in your dashboard.
Then go to Posts -> Add New (or Pages -> Add New) and you will see the Exclude from Search Results option which you can checkmark, and that is all you need to do to make your post or page unsearchable.
You can browse the list of your published posts and edit each one you need to restrict the search results to. Just go to Posts -> All Posts -> (Post Name) and exclude a chosen post from the search results just checking the definite option.
After that you can go to Settings -> Search Exclude and you will see the list of excluded posts or pages.
Hope this article was helpful.
Hi! I’m an experienced writer exploring WordPress for more than 6 years. I’m happy to share my knowledge and ideas with you and I hope you join me.
Cheers,
Melany H.