How to Add RSS Feed with a Route?

Using the RSS Plugin, I’d like to add an RSS feed to a site, but instead of setting up an invisible ‘feed’ page and template, I wanted to do it using a custom route.

I’ve tried the following, but it doesn’t seem to work…:

c::set('routes', array(
  array(
    'pattern' => 'rss',
    'action' => function(){
      return page('blog')->children()->visible()->filterBy('pub_date','<=',date('Y-m-d'))->sortBy('pub_date','desc')->limit(10)->feed(array(
        'title'       => 'Latest News',
	'description' => 'the latest news from our blog',
	'link'        => 'blog',
	'datefield'   => 'pub_date',
	'textfield'   => 'teaser'
        ));
      }
    )
));

Looking through the routing docs, I saw that the routing ‘action’ function must return either a page, or a response object, so I tried this…:

[...]
 'action' => function(){
      $output = page('blog')->children()->visible()->filterBy('pub_date','<=',date('Y-m-d'))->sortBy('pub_date','desc')->limit(10)->feed(array(
        'title'       => 'Latest News',
	'description' => 'the latest news from our blog',
	'link'        => 'blog',
	'datefield'   => 'pub_date',
	'textfield'   => 'teaser'
        ));
         return response($output,'xml',200);
      }

…but that doesn’t work either.

I know there must be an easy way to do this, but I can’t figure it out. Would be very grateful if someone could point me in the right direction…

Worked it out - I wasn’t creating the response object properly. Full code is:

c::set('routes', array(
  array(
    'pattern' => 'rss',
    'action' => function(){
      $output = page('blog')->children()->visible()->filterBy('pub_date','<=',date('Y-m-d'))->sortBy('pub_date','desc')->limit(10)->feed(array(
        'title'       => 'Latest News',
	'description' => 'the latest news from our blog',
	'link'        => 'blog',
	'datefield'   => 'pub_date',
	'textfield'   => 'teaser'
        ));
      $r = new Response($output, 'xml', 200);
      return $r;
      }
    )
));

Works like a charm!

Thanks for sharing!

You’re missing a closing ' in the description :wink:

Thanks for pointing this out.