For a multisite WordPress site, how can I access a tag feed across all subsites?

For the basics, I followed this guide I found on Google here:

A multisite feed is complicated by the fact that you have to collect and filter posts from multiple blogs yourself. To simplify some of the naming, let’s assume I want to collect all posts tagged foo.

I wrote a couple classes to manage this:

  • FooTagFeed
  • FooFeedPost

The code is a too long and inelegant to include here but I’ll stub out the code to guide anyone confronting a similar problem.

Added this to the bottom of my theme’s functions.php file:

# content/themes/main-theme/functions.php

/***************************************************
* Multi-Site Feed
* Based on http://www.wpbeginner.com/wp-tutorials/how-to-create-custom-rss-feeds-in-wordpress/
***************************************************/
add_action('init', 'add_multisite_foo_feed');
function add_multisite_foo_feed() {
  // Args: path (/feed/foo), callback (function below)
  add_feed('foo', 'build_foo_tag_feed');
}
function build_foo_tag_feed() {
  header('Content-Type: ' . feed_content_type('rss2') . '; charset=" . get_option("blog_charset'), true);
  get_template_part('foo_tag_feed');
}

And then my feed classes:

# content/themes/main-theme/foo_tag_feed.php

Class FooFeedPost {
    function __construct($wp_post) {}

    function as_rss_item() {}
}


class FooTagFeed {
    function __construct($wpdb) {
        $this->db = $wpdb;
    }

    function as_rss2() {
        $feed_posts = $this->fetch_posts_tagged_foo();

        // Sort by post date in DESC order.
        // Source: https://stackoverflow.com/a/10159521/6763239
        // Sorts in place and returns boolean.
        usort($feed_posts, function($a, $b) {
            return $a->timestamp < $b->timestamp;
        });
        $feed_posts = array_slice($feed_posts, 0, $this->item_limit);

        return $this->format_as_rss2($feed_posts);
    }

    function fetch_posts_tagged_foo() {
      $feed_posts = array();
      $blog_ids = $this->fetch_blog_ids();

      foreach ( $blog_ids as $blog_id ) {
          switch_to_blog($blog_id);
          $site_posts = $this->fetch_posts_tagged_foo_by_blog($blog_id);

          foreach ( $site_posts as $wp_post ) {
            $feed_posts[] = new FooFeedPost($wp_post);
          }

          restore_current_blog();
      }

      return $feed_posts;
    }

    function format_as_rss2($feed_posts) {}

    function fetch_blog_ids() {}

    function fetch_posts_tagged_foo_by_blog($blog_id) {}
}


$foo_feed = new FooFeedPost($wpdb);
echo $foo_feed->as_rss2();

The feed would then be served at: https://my-multisite-blog.com/feed/foo

If you’d like to see more of the code, ping me and I’ll try to include a link to a gist or something.