Technology WordPress Tips & Tricks

How to Exclude Pages from WordPress Search Results

Sometimes certain pages should not show up in your site's search results. Here is how to exclude pages from WordPress search, so visitors find the content that matters and skip the pages you would rather keep out of view.

Praveen Chauhan Praveen Chauhan 2 min read

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.

Get a FREE Consultation

Let's build something that lasts.

Share what's on your mind — a clear brief, a half-formed idea, or just a sense that something needs to change. We'll listen first, ask the right questions, and point you toward what's actually worth building.

We take on a handful of projects each quarter,ones where we can truly make a difference.

  • Receive a human response within 24 hours
  • Get a detailed scope and quote upfront
  • We're happy to sign an NDA upon request

    Free 30-Min Strategy Call

    Your Name *

    Your Phone No *

    Work Email *

    Your Budget*

    Project Details *