How to Exclude Pages from WordPress Search Results

Posted on July 12th, 2010 by in Tutorials | 12 Comments  
How to Exclude Pages from WordPress Search Results

By default, WordPress Search feature displays published posts and published pages in search results. Often when users are looking for something in a blog, it is most likely a post rather than a page. In this article, we will show you how to make your search more relevant and less crowded by excluding pages from WordPress search results.

First open your theme’s functions.php file and paste this code:

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

    add_filter('pre_get_posts','SearchFilter');

Explanation: This code just searches for posts through setting the post_type. You can also make it do the opposite by setting the post_type to pages, so it only return pages in the search result.

Source: Bavotasan

If you want to exclude individual pages from WordPress search results, then use the plugin: Simply Exclude.

About

Editorial Staff at WPBeginner mainly Syed and David.

Post comment as twitter logo facebook logo
Sort: Newest | Oldest
luckyankit 5 pts

Well just wanted to say thank you for this... wonderful article

gormanIT 5 pts

Can you alter this function to exclude specific pages/posts from search? Ive been searching for this functionality and havent found anything.

Thank you so much. This was super helpful, fixing my problem with the speed of a cut and a paste (and a test)..

Success in all your ways!

Michael.

Well, that's almost perfect. I searched and found that many site's offering us to hardcode the category ids to search id but this is cool. One question, i have to do the pagination myself so when i add this filter i won't get offset issues .. right?

No, you should not have offset issues.

You need to modify this sentence to say "page" instead of "pages":

You can also make it do the opposite by setting the post_type to pages, so it only return pages in the search result.

Hi
may I put your tutorials in my blog with a link to wpbeginner.com? my blog is in Farsi and I think many persian users need these tips.
thanks a lot

No you may not translate any of our tutorials entirely. You may write a summary and then link to our site.

This hack excludes not only pages from search results, but also other custom post types. So if we have many custom post types in our WP site, we can put them in the statement like this:

$query->set('post_type', array('post', 'custom-post-type'));

Thanks Rilwis, just what i needed!

Tweets about us: