Jul
08
2010

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.

If you liked this, please share it.

Tags: , , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/diTqGN

Discussion 1 Comment

  1. aban on July 14, 2010 at 5:32 pm

    Thank your for sharing…

    I have re-written your post in Bahasa Indonesia on my blog about this tips and surely the credit goes to you :)

Leave a Reply

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

*


To enter code in the comment box, please place it between <pre lang="php"> </pre> tags. You don't have to convert any characters to their hex/HTML code. Just add your code the way you would to any code editor.