Exclude Pages from WordPress Search Results

February 7, 2021 • , • Published By • 2 minute read

After performing a search on your WordPress website, have you noticed that pages are included in the search results? Would you prefer to exclude pages from your search results since they might not be as relevant? Let’s learn how!

Table of Contents

Exclude Pages

To exclude pages from your WordPress search results, we’ll make use of a filter hook called pre_get_posts.

Navigate to Appearance > Theme Editor and open the template file in your theme called functions.php. Add the following code to it.

add_filter( 'pre_get_posts', 'my_pre_get_posts' );

The second parameter in the add_filter function is the name of the function you want to call. Let’s create that function now. It receives the WP_Query instance as an argument. Let’s call it $query.

// Adjust post content.
function my_pre_get_posts( $query ) {

}

Let’s continue adding to the function. First, we’ll ignore doing anything if this is an admin page using the is_admin function. We also want to ignore doing anything if the current query is not the main query using the is_main_query function.

// Don't apply filter if it's an admin page or current query is not the main query
if ( is_admin() || !$query->is_main_query() ){
  return;
}	

Now we’ll check if the current query is a search query using the is_search function. If it is, we’ll set the post type to just include posts, which will exclude pages from search results.

if ( $query->is_search() ) {
  // Exclude pages from search results.
  $query->set( 'post_type', 'post' );
}

Finally, we return the adjusted query.

return $query;

You have successfully excluded pages from your WordPress search results!

Keep in mind that if you switch to a different theme, you would lose this functionality because it was added to your current theme’s functions.php file. If you want this functionality to persist, make it a WordPress plugin instead.

Related Articles
About the Author

Front End Developer

https://nightwolf.dev