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;
}
?>
Comments
Davy plz mention the place where to put this code.
A very handy article if you are looking to theme your Search box on your drupal site.
I think you should learn Drupal module development. I can't explain the whole deal here in each post. A good book is Pro Drupal Development or Drupal's handbook
This looks like a simple and clear technique, but I have no idea where to put this code. I'm relatively new to Drupal but have been doing PHP for years, so I'm sure I could figure it out. But if you could say which files to save this into, and what steps to take in the Drupal admin to enable it, it would save me a couple hours and would make this article a lot more useful. Thank you, Paul
Hi Davy,
I saw your post and was wondering if this could help me to solve a bug in the drupal panels module when using panels as the front page. See also http://drupal.org/node/212442
As I am using panels to create a new homepage every week, I don't have an rss feed on http://www.consumentenpagina.be which is pretty annoying. I am now looking into making the feed manually but of course that is no solution.
But I have no idea where to start with your code as my development experience with Drupal and php is limited. Any suggestions?
Thx.
Erik
Post new comment