November 17th, 2010
There are plenty of plug-ins and widgets available to pull feeds into your sidebar, or other areas of your site. But if you want more control over how these feeds are presented, you may want to add them directly to one of your template files.
WordPress used to use Magpie RSS to parse RSS feeds, but now it uses Simple Pie. To add a feed to a template just include the following code into your template before or after the WordPress loop, as desired. In this example I'm using the feed from my Web Development Blog and have set it to show the 5 most recent headlines. Just replace my feed with yours and adjust the number of headlines you wish to include. I've included this code on the bottom of the blog home page where it says "Recent posts from the Web Development Blog," if you would like to see an example.
<?php // Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/feed.php');
// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed('http://feeds2.feedburner.com/hacwebdev');
if (!is_wp_error( $rss ) ) : // Checks that the object is created correctly
// Figure out how many total items there are, but limit it to 5.
$maxitems = $rss->get_item_quantity(5);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0, $maxitems);
<?php if ($maxitems == 0) echo '<li>No items.</li>';
// Loop through each feed item and display each item as a hyperlink.
foreach ( $rss_items as $item ) : ?>
<a href='<?php echo $item->get_permalink(); ?>'
title='<?php echo 'Posted '.$item->get_date('j F Y | g:i a'); ?>'>
<?php echo $item->get_title(); ?></a>
<?php endforeach; ?>
Categories: WordPress Tips
No Comments »
No comments yet.