Search is a very important feature on any website, many site owners want that when the user uses the search feature, they get the exact and accurate results of their search query in a professional and clean manner.
By default, the search feature in WordPress displays the results by filtering the database or all the pages present in the site. In which many times the test or demo pages created by us start appearing which should not be accessible to users.
There are a few ways to avoid this in WordPress. But yes, this method is for those people who want to avoid adding an extra plugin to their site and want to exclude some specific pages from the search results page through simple code.
Excluding Pages From WordPress Search Results Using Code
To exclude specific pages from the search results in WordPress, you’ll need to add the below custom code to your WordPress theme or functions.php
file.
add_filter( 'pre_get_posts', 'exclude_pages_search_when_logged_in' );
function exclude_pages_search_when_logged_in($query) {
if ( $query->is_search && is_user_logged_in() )
$query->set( 'post__not_in', array( 1, 2, 3, 4, 5 ) );
return $query;
}