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!

4 Responses

Sep 13 2011 12:44

Hi,

Thank you for this snippet! But so far it does not seem to work. I am using WP 3.2.1.

I want to remove 3 pages from my search results. However, the snippet does not seem to be working for pages. I have added in the IDs of my pages, but they still appear in my search results. I have also tried it for posts, but it does not remove posts from the search results.

Any ideas? (There is no date on this snippet, so I am not sure how old it is)

Nov 29 2011 14:22

@nicholas
the code in this post is partially wrong, if you want to exclude a cat (eg cat id 5 and 24) you have to set
$query->set(‘cat’,'-5,-24′);
if you want to exclude a post set
$query->set(‘p’,'-250′);

bye

Dec 31 2011 02:53

Is there a way to exclude a specific page by Page ID #?

Jan 13 2012 22:17

Yes. To exclude a page change

$query->set(‘cat’,’8,15′);

to

$query->set(‘post__not_in’, array(215));

where 215 is the ID of the page you want to exclude. You can exclude as many pages as you want, just add the IDs to the array. You can also use this to exclude posts.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required