HOW-TO: Include an RSS feed in WordPress

January 8th, 2006

There’s a lot of documentation about how to syndicate your WordPress site’s content using RSS. It’s a bit harder to find out how to include an RSS feed from another site in your site.

Fortunately, the developers of WordPress have already included all the necessary ‘plumbing’ (they use it to update the Dashboard). Bundled with WordPress is a version of MagpieRSS - a well-respected RSS interface written in php. All you need to know is how to invoke it from your own pages.

This is easiest to illustrate with an example. The following code will pull in the first five items of the latest world news from the BBC:

<?php
require_once (ABSPATH . WPINC . '/rss-functions.php');

$url = 'http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml';
$rss = fetch_rss( $url );
if ( $rss ) {
echo "Title: " . $rss->channel['title'] . "<p>";
echo "<ul>";
$i = 1;
foreach ($rss->items as $item) {
$href = $item['link'];
$title = $item['title'];
$description = $item['description'];
echo "<li><a xhref=$href>$title</a><br />$description</li>";
if ($i == 5 ) break;
$i = $i + 1;
}
echo "</ul>";
}
?>

All you need to do now is to create a template including this code. Copy page.php (or index.php if your theme hasn’t got a page.php) to rss_feed.php, and tell WordPress to use it as a template by adding the following code to the top of your new file:


<?php
/*
Template Name: RSS Feed
*/
?>

Insert the RSS code wherever you want it to appear in the page, save it, and then select this new template in the Page Editor.

You can see what the result looks like on the RSS Feeds page