Exclude a Category from a WordPress Search

Screen Shot 2013-10-04 at 11.15.20 PMI wanted to exclude some of my pages from the search results. I assigned the uncategorized category to all of them. Then I could use the following code to exclude that category.

In my case, I used the ‘uncategorized’ category for the posts I didn’t want to show. The category ID for ‘uncategorized’ is 1 on my site. To exclude the category I need to put a minus sign in front of the category number.

I added a filter for the pre_get_posts WordPress function and check to see if the query is a search. If it is, then the category is set to the category number to include it in the search.

To exclude a category from the results, just put a minus sign in front of the category number.

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

add_filter('pre_get_posts','SearchFilter');
//

If I wanted more than one category excluded or included I would use a comma like this:

//
function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('cat','-1,-5');
    }
    return $query;
}

add_filter('pre_get_posts','SearchFilter');
//

The add_filter statement hooks our SearchFilter function to the pre_get_posts action. All the code should go in the functions.php file.

2 thoughts on “Exclude a Category from a WordPress Search”

  1. This is what I was looking for. I wanted to exclude 1 category from the search results. There is no such feature inside wordpress itself. Now I know how to deal with it. It looks like adding the code to the file – will it disappear when updating the theme? Will you need to add it every time you update your theme files?

    1. It depends on where you put the code. You could create a WP plugin and put the code in it, then you don’t have to worry about updates overwriting your code. You could also create a child theme and put the code in the functions file, then when you update, the parent theme is updated, but it won’t override the code in the child theme.

Leave a Comment

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

Scroll to Top