It's actually very easy to import RSS Feeds and display them on your WordPress Site, e.g. in the sidebar. WordPress, as well as PHP, provides functions to fetch the feed, parse it and provide it to the user itself.
The opportunities are versatile, for example you can import your recent flickr photos or display the latest articles from partner sites and so on. I provide an example of importing your own RSS feed, for example to display it on your front page instead of the loop. This has the benefit of querying the database only one time, as oppose to the multiple times it would be executed via the loop.
<?php get_header(); ?>
<?php require_once (ABSPATH . WPINC . '/rss-functions.php'); ?>
<?php $today = current_time('mysql', 1); ?>
The line should be familiar, it imports the header of the current theme. Then we include rss-functions.php from WordPress to get the RSS functionality. Also, we get the current date for later reference.
<div class="main">
<h2>Recent Postings</h2>
<?php
$rss = @fetch_rss('http://www.jeriko.de/feed/');
if ( isset($rss->items) && 0 != count($rss->items) ) {
Nothing special at first, just a simple header to make clear what we're showing. Then we get the RSS feed via @fetch_rss from the given URL. A simple check will make clear if the feed actually has entries.
<ol>
<?php
$rss->items = array_slice($rss->items, 0, 5);
foreach ($rss->items as $item ) {
?>
<li>
<a href='<?php echo wp_filter_kses($item['link']); ?>'>
<?php echo wp_specialchars($item['title']); ?>
<small>—
<?php echo human_time_diff( strtotime($item[’pubdate’], time() ) ); ?>
<?php _e(’ago’); ?>
</small>
</li>
Now here comes the fun part, we split the feed into the entries and will get the five newest ones. If you want more, change the appropriate parameter in array_slice. Then we will output each of the entries via foreach. Everything inside this loop are just special formattings of the specific parts of an entry, it's up to you how you want them to be displayed.
<?php
}
}
?>
</ol>
This closes every loop as well as the unordered list. And thats pretty much it, it will display the titles and dates of the last five entries.
Below is the structure for an RSS feed provided by WordPress:
- title (the title of the posting)
- link (the permalink of the posting)
- pubDate (the date on which the posting was made)
- dc:Creator (the author of the posting)
- description (what would be shown as the excerpt of the posting, either the beginning of the posting or the excerpt itself)
- content:encoded (the content of the posting)
If you use the code above, you access this fields via $item['fieldname'].
One thing to remember: If you use RSS feeds from other sites than your own, make sure that you either (1) clearly mark them as external entries and not your own and/or (2) ask the original author of the feed for permission to use them on your site.