Jul
08
2010

Excluding Pages from WordPress Search

by   |  Posted in Tutorials  |  6 comments

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.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

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

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

Discussion 6 Comments

  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 :)

  2. Garnett Postell on December 2, 2010 at 6:56 am

    Very nice Post i like it

  3. OkamaGraham on December 3, 2010 at 4:41 am

    hi me and my friend have tried to connect your rss feed but i got an site error. Ensure you have look and handle the error as pal certainly like to Add your blog site to my rss news feed. By the way very good web site you got here. Greetings

  4. Jason Gegere on January 26, 2011 at 3:43 am

    Have there been some changes with WordPress 3.0? I have moved this snippet into the themes functions.php file and it does not work.

    If I add this code within the while (search) loop only the posts are then returned.


    if ($query->is_search) {
    $query->set('post_type', array( 'post', 'classified' ));
    }

    I am using the Twenty Ten theme. Thanks is advance.

    • c.bavota on January 26, 2011 at 10:16 am

      The whole code snipped above needs to be added to the functions.php file outside of every other function and between PHP tags. I use it on multiple sites and it works, even in 3.1.

  5. kamagra oral jellys on February 2, 2011 at 8:11 am

    Yes work with WordPress is not very convenient. Recently, I encountered the same problem. Thank you for your advice and your help.