DEV Community

Cover image for Exclude Pages from WordPress Search Results
nightwolfdev
nightwolfdev

Posted on • Originally published at nightwolf.dev

Exclude Pages from WordPress Search Results

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!

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' );
Enter fullscreen mode Exit fullscreen mode

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 ) {

}
Enter fullscreen mode Exit fullscreen mode

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;
}   
Enter fullscreen mode Exit fullscreen mode

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' );
}
Enter fullscreen mode Exit fullscreen mode

Finally, we return the adjusted query.

return $query;
Enter fullscreen mode Exit fullscreen mode

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.


Visit our website at https://nightwolf.dev and follow us on Facebook and Twitter!


Top comments (0)