Excluding Pages from WordPress Search

When people visit my site and do a search, I assume they’re looking for results within my posts and not in any of my static pages. Too bad WordPress automatically searches through both. In order to exclude pages from the WordPress search, you need to add a small piece of code to the functions.php file. I found a solution on WP Recipes but I was not a fan of having to add all of my category IDs in order to make it work. So I decided to modify it a bit.

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

I forced it to just search for posts through setting the post_type. You can also make it do the opposite by setting the post_type to page.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie