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 IaaS engineer in Sydney, Australia who refers to himself in the third person in bios. Wait, not BIOS… my brain should be EFI by now.

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

You can leave me a comment by contacting me, and I might publish your thoughts. Please read the FAQs first though.

If you found this post helpful or entertaining, you can shout me a coffee or buy some silly merch. Thanks!