Exclude pages or posts from your WordPress search

If you are using WordPress’ default search engine which allows you and your visitors to search for the content on your website, you should know that by default, WordPress goes through posts and pages to find and display the results.

In most cases, you will want your visitors to be able to search through your posts while results coming from pages might only distract a typical “searcher”.

If your pages contain contact information, maps, author info, etc. you probably don’t need those pages to be included in the search results.

How to exclude pages from WordPress search

While there is no easy way of telling WordPress to exclude a post type from search results, you will need to that by yourself:

    1. Open functions.php
    2. Copy and paste the following code in the file:
    3. function SearchFilter($query) {
      if ($query->is_search) {
      $query->set('post_type', 'page');
      }
      return $query;
      }
      
      add_filter('pre_get_posts','SearchFilter');
    4. Save changes

    After you have made the changes and save them, you are free to visit your website and test the search engine. If everything’s ok, you shouldn’t be able to find any information from your pages in the search results, i.e., you successfully exclude pages from WordPress search results.

    How to exclude posts from WordPress search

    In the introduction, we told you that WordPress goes through posts and pages and assumed you don’t want pages to show in the results. But what if you don’t want posts to be included in those results? If so, you can make one simple change to the code and exclude posts instead of pages:

    Again, you will need to repeat those 3 simple steps shown above, but with a simple change in line #3. Instead of setting post type to “page”, you have to set it up to “posts”:

    $query->set('post_type', 'posts');

    Don’t forget to save everything and you’re done.

    If you want only certain pages to be excluded while the other ones stay in the search results, please see the following article. If you want to know more about modifying WordPress, check the WordPress basics, see more tutorials that will help you level up your skills, and check our other resources that will help you to become a better webmaster.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

2 thoughts on “Exclude pages or posts from your WordPress search

  1. To limit searches only to posts, please use the following code:

    function custom_search_filter($query) {
    if ($query->is_search) {
    $query->set(‘post_type’, ‘post’);
    }
    return $query;
    }
    add_filter(‘pre_get_posts’,’custom_search_filter’);

Leave a Reply

Your email address will not be published. Required fields are marked *