Having the search option in the website means if you search for some irrelevant terms, it will show you some irrelevant items too, and in my case it will show the test pages. I was looking for the best solution for excluding some pages from showing in the result page of the search. There are 2 solutions I prefer doing:

  1. Excluding pages from search results using Search Exclude WordPress plugin. This is one of the best plugins that will take care of that by adding a check box to your page’s backend and simply provides this option.
  2. Excluding irrelevant items without using the plugin: in this method which I currently implemented, by adding the code below to your functions.php you can exclude the pages.
add_action( ‘pre_get_posts’, ‘my_search_exclude_filter’ );

function my_search_exclude_filter( $query ) {

if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) {

$query->set( ‘post__not_in’, array( 9564, 1213  ) );}

}

You have to address the ID of the page you want to exclude by going to the page’s backend and use the ID in the URL of the page as below:

https://Websiteurl/wp-admin/post.php?post=9564&action=edit

In this example, 9564 is the page ID.