Limit Your WordPress RSS Feed To One Category
When designing Anderson Web Solutions, I decided to use Posts for both news items and Portfolio entries. There were several advantages to doing this, but one issue I found was that everything was being thrown together in the RSS feed. I decided to look into filtering the RSS feed to only show posts from the News category. Here’s how it works.
As with just about anything in WordPress, you can use Actions and Filters to customize the way WordPress RSS Feeds. I chose to filter the query because it already has built in category filtering functionality. First I hooked into the query filter.
add_filter('pre_get_posts', 'filterRSSQuery');
Then I created a function called ‘filterRSSQuery’ which does just what the name suggests.
function filterRSSQuery($query) {
if ( $query->is_feed ) {
$query->set('category_name', 'News');
}
return $query;
}
The code is pretty straight foreward, but here’s a breakdown. First we test to see if the query is for a feed (we don’t want to do this filtering anywhere else). Then we set the ‘category_name’ argument to ‘News’ (you would change this to whatever category you want to show up). Finally, you return the modified query object.
Overall, this is pretty simple, but extremely powerful.
[...] WordPress: Limit Your RSS Feed To One Category [...]
Hi Will,
Can you elaborate on how and where to include this? What files?
Thanks,
Matt
You would most likely put this in your functions.php file for your theme, but you could also put it in a plugin file. It would work either way (though in my mind the functions.php file makes more sense).
Thanks for this! It works great!
Hey there
I was wondering where you would put this in the functions.php file and would the add filter line need to be right next to the query code you put?
Placement in the functions.php file is pretty flexible, but I usually try to place my newest changes at the beginning. The add_filter line should go after the function. Placing it directly after the function is the best idea because it makes it clear what’s going on.