Sometimes we need to exclude a few unimportant categories from our main feed or other wordpress pages. A quick search through the web, you will arrive at wprecipes’ tutorial, which unfortunately happens to be erroneous because wrong function was used (as of 15 Dec 2011). Anyway, in this blogpost I am gonna show how to exclude categories in RSS Feed, as well as Homepage, Search Page and more.
There are a number of ways to achieve what we want, but the best and cleanest method is to exclude using WordPress Action Hook: pre_get_posts. Using this action hook, we can easily exclude any categories in all wordpress generated pages.
First thing you need to do is find the category IDs that you want to hide. WPrecipes explains this pretty well.
Let’s say you want to exclude category 3, 4 and 5. Open your theme’s functions.php, paste these codes:
function mytheme_exclude_cats($query) { if ($query->is_feed) { $query->set('cat','-3,-4,-5');//seperate by comma } return $query; } add_action('pre_get_posts','mytheme_exclude_cats'); |
You can run var_dump($query) inside the function to learn more about what the object holds.
Just simply change “is_feed” to “is_home”:
function mytheme_exclude_cats($query) { if ($query->is_home) { $query->set('cat','-3,-4,-5');//seperate by comma } return $query; } add_action('pre_get_posts','mytheme_exclude_cats'); |
Just simply change “is_feed” to the following:
is_feed – in RSS feed page
is_home – in blog homepage
is_category – in category page
is_tag – in tag page
is_search – in search page
is_comment_feed – in comment RSS feed page
is_author – in author archive page
For example, to exclude category 3, 4 and 5 in both RSS Feed and Search page, it will be just as easy as:
function mytheme_exclude_cats($query) { if ($query->is_search || $query->is_feed) { $query->set('cat','-3,-4,-5');//seperate by comma } return $query; } add_action('pre_get_posts','mytheme_exclude_cats'); |
Hope this helps.


To make this a little more transparent and not break the ability to allow category specific feeds, you can change to this (adding “&& !$query->is_category” to the if statement):
function mytheme_exclude_cats($query) {
if ($query->is_feed && !$query->is_category) {
$query->set(‘cat’,'-5, -8′);//seperate by comma
}
return $query;
}
add_action(‘pre_get_posts’,'mytheme_exclude_cats’);