Excluding WordPress categories

Internet

I can confirm adding the following code to the functions.php in my current theme prevents posts from certain categories appearing on the home page, and the main site RSS feed. In this case we're filtering category ID 5:

function myFilter($query) {
  if ($query->is_feed || $query->is_home) {
    $query->set('cat','-5');
  }
  return $query;
}
add_filter('pre_get_posts','myFilter');

If you only want to filter categories from the home page, simply remove the $query->is_feed || condition, and vica versa.

This little change really allows WordPress to be used as a simple CMS by allowing you to separate material and provide category feeds for different types of posts. I'll be using this so regular readers subscribed to my main RSS feed don't get any of my anime posts from my blog that I'll be importing from my university intranet.

Thanks to Scott Jangro for this great tip.

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.