Here is some code that allows you to hide pages from WordPress search based on the pages using a specific template.
Let’s say you had a Members Only section that was accessible by logged in members to your site. But what happens when this locked down content appears in your site’s search results? Below is a way you can hide these pages from appearing in the search results.
Step 1)
Create a template or clone / copy an existing template and call it something like Exclude Search Template (exclude.php) or Members Template (members.php). Place (e.g., FTP) your template into your child theme’s directory.
Now place the below code into your child theme’s function file. Makes sure the name of the template appears in the code below.
function exclude_page_templates_from_search($query) {
global $wp_the_query;
if ( ($wp_the_query === $query) && (is_search()) && ( ! is_admin()) ) {
$query->set(
'meta_query',
array(
array(
'key' => '_wp_page_template',
'value' => 'members.php',
'compare' => '!='
)
)
);
}
}
add_filter('pre_get_posts','exclude_page_templates_from_search');
That’s it, your done. Now if you find members content in your search results, you can click on these pages and change them to use the Members template and they will not appear in the search results again.