RSS

Creating your own RSS feeds with Drupal's node_feed

If you need to create your own RSS feed in Drupal, you can do this in only a few lines of code using the same function the default Drupal feeds are generated.

This function is called node_feed($nodes = 0, $channel = array()) and it expects a database query result resource generating the required node identifiers to generate the RSS code.

The following example should give you enough information to use this in your own module. In this example I will only include the nodes of type 'story' in the RSS feed.

<?php
function mymodule_rss() {
  $nodes = db_query_range(db_rewrite_sql('SELECT n.nid FROM {node} n WHERE n.type = \'story\' AND n.status = 1 ORDER BY n.created DESC'), 0, variable_get('feed_default_items', 10));
  node_feed($nodes);  
}

/**
 * Implementation of hook_menu().
 */
function mymodule_menu($may_cache) {
  if ($may_cache) {
    $items[] = array('path' => 'rss.xml', 'title' => t('RSS feed of latest stories'),
      'callback' => 'mymodule_rss',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
  }
  return $items;
}
?>

We can finish this by adding our feed as a syndication link in our HTML header using the Drupal core function drupal_add_feed($url = NULL, $title = '').

To achieve this in our example we alter the previously mention hook_menu implementation as follows:

<?php
/**
 * Implementation of hook_menu().
 */
function mymodule_menu($may_cache) {
  drupal_add_feed(base_path().'rss.xml', 'RSS feed of latest stories';
  
  if ($may_cache) {
    $items[] = array('path' => 'rss.xml', 'title' => t('RSS feed of latest stories'),
      'callback' => 'mymodule_rss',
      'access' => user_access('access content'),
      'type' => MENU_CALLBACK);
  }
  return $items;
}
?>
Written on February 04, 2008 at 14:56, tagged as Drupal, module development, RSS, tutorial

About

drupalcoder.com is a blog on all things Drupal in specific and LAMP on OS X in general. It is maintained by Davy Van Den Bremt, a Belgian (Drupal) web developer and designer living in Ghent. The goal of this blog is to log all interesting things that have crossed the writer's path while developing Drupal sites. You can read all about Davy's professional activities on his LinkedIn profile. If you want to get in touch, use the contact form.