Search

How to Exclude Pages from WordPress Search Results

Listen to this article

Search-WordPress-Websites-smallBy default, WordPress Search feature displays published posts and published pages in the search results. Often when users are looking for something in your blog, they are most likely looking for a post rather than a page. It makes sense to display only posts in your search results. Or may be there are certain posts you want to avoid from being shown in the search results. These could be old posts, or irrelevant results.

In this article, we will show you how to make the search feature on your WordPress site more relevant, and less crowded, by excluding pages from WordPress search results. You can use the same function to exclude custom post types as well.

First open your theme’s functions.php file and paste this code, you could also create a custom plugin and add the code there:

function SearchFilter($query) {
           if ($query->is_search) {
                  $query->set('post_type', 'post');
          }
         return $query;
 }
add_filter('pre_get_posts','SearchFilter');

[space]

How it Works?

This code uses the pre_get_posts hook to filter search results. Instead of the default condition, we have set the post_type to post. This limits the search only to posts on your site. You can also make it do the opposite by setting the post_type to pages (or any other custom post types), so it only return pages in the search result.

Nevertheless, we all can agree that the search functionality on a WordPress site is fairly limited. Instead we can add a much better search functionality using a WordPress search plugin or using an advanced search server such as Apache or Solr.

Praveen Chauhan

Praveen Chauhan

Get The Latest Updates

Subscribe to our Newsletter

A key to unlock the world of open-source. We promise not to spam your inbox.

Suggested Reads

How to Make Responsive Tables using CSS without Tag
Join our 55,000+ Subscribers

    The Wisdm Digest delivers all the latest news, and resources from the world of open-source businesses to your inbox.

    Suggested Reads