How to Exclude Categories from RSS Feed with Functions.php in WordPress

WPTurbo » Snippets » How to Exclude Categories from RSS Feed with Functions.php in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you looking to customize the content of your WordPress RSS feed by excluding certain categories? By default, WordPress includes all categories in the RSS feed, but sometimes you may want to exclude specific categories from being included. In this article, we’ll guide you through the process of excluding categories from your RSS feed by using functions.php. With this handy tip, you’ll have full control over the content that is displayed in your RSS feed. Let’s dive in!

					function wpturbo_exclude_categories_from_rss_feed( $query ) {
    if ( $query->is_feed ) {
        $excluded_categories = array( 1, 2, 3 ); // Change these numbers with the category IDs you want to exclude
        $query->set( 'category__not_in', $excluded_categories );
    }
    return $query;
}
add_filter( 'pre_get_posts', 'wpturbo_exclude_categories_from_rss_feed' );
				

The code snippet provided allows you to exclude specific categories from the RSS feed of your WordPress site. This can be useful if you want to limit the content that is syndicated through the feed or if you have specific categories that you don’t want to appear in the feed.

Let’s break down the code step by step to understand how it works.

The first part of the code defines a function called wpturbo_exclude_categories_from_rss_feed(). This function takes in a parameter $query which represents the query object of the current request.

Inside the function, we check if the query is for a feed by using the condition $query->is_feed. This ensures that the code is only executed when the request is for an RSS feed.

Next, we define an array called $excluded_categories which contains the IDs of the categories that we want to exclude from the feed. You can add or remove category IDs as needed.

We then use the $query->set() method to modify the query parameters. In this case, we use the category__not_in parameter to exclude the categories specified in the $excluded_categories array.

Finally, we return the modified query object.

To apply this functionality, we need to hook the wpturbo_exclude_categories_from_rss_feed() function into the pre_get_posts filter. This filter allows us to modify the query object before it is used to retrieve posts.

By adding the line add_filter( 'pre_get_posts', 'wpturbo_exclude_categories_from_rss_feed' );, we ensure that the wpturbo_exclude_categories_from_rss_feed() function is called whenever a feed query is executed.

Once you have added this code to your theme’s functions.php file or a custom plugin, the specified categories will be excluded from the RSS feed of your WordPress site.

Register an account to save your snippets or go Pro to get more features.