Sometimes you have a category in your WordPress blog which you want to exclude category posts from appearing in blog’s homepage and also want to hide posts belong to this category from your main RSS feed.
WordPress has a very simple solution for our little problem. WordPress provides a hook pre_get_posts that called just after the query variable object is created, but just before the actual query is run. The pre_get_posts gives us access to the $query object so we can modify it as we prefer. Using this hook we will filter WordPress query to exclude posts from specific category and restrict them from appearing in blog feed.
Simply paste this code snippet in your theme’s functions.php file to exclude category posts from blog RSS feed. In the following code snippet, the numbers 52 is the category IDs that we want to exclude and make sure to add a minus sign in front of category ID.
// exclude category posts from rss feed
function wcs_exclude_category_from_feed( $query ) {
if ( $query->is_feed ) {
$query->set( 'cat', '-54' );
}
return $query;
}
add_filter( 'pre_get_posts', 'wcs_exclude_category_from_feed' );
To exclude category posts from multiple categories in your WordPress RSS feed, you can specify category IDs separated by comma. Here is an example to excluding posts from multiple categories.
// exclude multiple categories posts from rss feed
function wcs_exclude_categories_from_feed( $query ) {
if ( $query->is_feed ) {
$query->set( 'cat', '-54, -73, -97' );
}
return $query;
}
add_filter( 'pre_get_posts', 'wcs_exclude_categories_from_feed' );