How To Exclude Pages In WordPress Search Results Page

WordPress, by default, when you search your site, it will display all of the posts and pages within the search result page. However, when the visitor to your site is searching within your site, they might be searching for the posts, instead of pages. So, what about excluding pages in search result page? Is it doable? Well, it is doable and hence here we will learn about how to exclude pages in WordPress search results page. So, let’s move ahead and learn about it, shall we?

How WordPress handles search results page?

WordPress, by default, as described previously, displays anything, ie, posts as well as pages in it’s search result too. However, if your site is heavily focused on blog posts then, displaying the pages in search results might not be great idea.

Also, the user is likely to search for posts, not the pages within your site. So, it might be great idea to exclude pages in WordPress search results page. So, let’s dive into it and learn about how to do so.

How to Exclude pages in WordPress search results page?

For this feature, open up your functions.php file of the theme and paste the below PHP code in that file to exclude pages in WordPress search results page:

function theme_slug_search_filter( $query ) {
if ( ! is_admin() ) { // Checking if currently on admin page, if not on admin page then proceed.
if ( $query->is_search ) { // If current page is search page then only proceed.
$query->set( 'post_type', 'post' ); // Search results page display content of posts only.
}
}

return $query;
}

add_filter( 'pre_get_posts','theme_slug_search_filter' );

What we have done in the above code is, we have hooked our custom function on: pre_get_posts hook. And for the remaining part, we have added the respective comments about what we have did onto those codes.

However, if you want to display the search results of pages only then, you can amend the above code from: $query->set( 'post_type', 'post' ); to $query->set( 'post_type', 'page' );.

You may also want to read:

  1. How To Create XML Sitemap For Your Site
  2. Tutorial On Creating WordPress Child Theme
  3. Minimal Files Required To Create New WordPress Theme
  4. Enable Multisite In WordPress
  5. Adding Featured Image In Your Post And Pages

Conclusion

If you have followed up this tutorial and became successful on about how to exclude pages in WordPress search results page more easily than before then, we can assume that you are not more familiar onto this than before. However, if you are still confused on it and want to know more about it then, do drop the comment below on the comment box and we will follow it up.

Post navigation

Bishal Napit

Bishal Napit is a WordPress theme developer from Tansen, Palpa, with a passion to learn more on WordPress.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.