WordPress Howto: Combine Categories into a RSS/Atom Feed

This was really pretty easy but I was surprised that WordPress apparently does not have the functionality to combine posts from two or more categories into one feed. Say you have five categories: Fishing, Hunting, Vegan Diet Tips, Feather Boas and Cleaning Automatic Weapons.

Say you want a feed that combines Hunting and Vegan Diet Tips. You'd think WordPress would easily offer something like that, but they don't. Here's how you do it.

 
function do_feed_custom()
{
    global $wp;
    $cats = explode ('|', $wp->query_vars['cat']);
    query_posts(array('category__and' => $cats,'posts_per_page'=>10));
    load_template( TEMPLATEPATH . '/feed-by-cat-rss2.php' );
}
 
add_action('do_feed_custom','do_feed_custom');
 

I put all that in my theme directory in a file called functions.php. You could make it a plugin if you wanted to.

You call it like this:


http://domain.org/?feed=custom&cat=37|5

Where 37 is the Hunting category and 5 is the Vegan Diet Tips category.

Now the feed has both, and there aren't any duplicates.

It's also very simple. The only thing I'm going to add is that the "load_template()" line refers to feed type that I just copied over from the standard WordPress library. I didn't need to re-write the actual feed at all, I wasn't customizing the feed fields or anything. I just wanted more than one category.

One other note: I used a pipe instead of a comma because of some weirdness in the depths of WordPress that rewrites URLs and re-urlencodes everything. So, if you use a comma, WordPress will change it to a url-encoded comma and it gets messier. It took me more time to figure that out than it did to write this function once I understood what was happening.

If you have any questions, I'm "ha17" on stackoverflow.com