Post Pic

How to: Exclude posts or pages from search results

Would you like to be able to control which post or pages must be exclued from searches on your WordPress blog? If yes, this recipe will probably help you a lot. Just read on.

To achieve this recipe, simply paste the following code on the functions.php file from your theme. In this example, posts with IDs 8 and 15 will be excluded from your blog’s search results:

function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('cat','8,15');
    }
    return $query;
}

add_filter('pre_get_posts','SearchFilter');

Credits goes to Kyle Eslick for this awesome hack!

11 Responses

Dec 22 2008 13:49

This is great! Excluding pages from search is a must in my case because pages ruins the display of some themes when it gets displayed in internal results.

Dec 22 2008 18:51

Great tip to keep in mind ;)

Dec 22 2008 19:01

Awesome hack, indeed.
REgards
Shane
twitter:shanearthur

Dec 27 2008 22:42

Wow… this is great when you have some posts that you want to be more… hidden [not private].

I think something like this could be implemented in a future version of WP :-)

Mar 31 2009 19:29

what about excluding categories from results?

Jul 16 2009 17:28

This code has removed all pages from search results. I am using Wordpress 2.8.1, is there an updated version of this code?

Jul 16 2009 19:51

@Chet: Weird problem. The code was made before 2.8 was released, so maybe it is the problem. I’ll have a look when I’ll have some time.

Sep 16 2009 12:21

Hi,
i use
$query->set(‘cat’,'-8,-15′);
for my WP 2.8.4 and it works fine when you don’t want to show the results for cat8 and cat15.

Oct 22 2009 11:57

The problem with this is a error that show up on Search Results when you find a image on media inside the dashboard :(

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required