DiggingIntoWordPress

by Chris Coyier & Jeff Starr

How to Import and Display Feeds in WordPress 2.8 and Beyond

Posted by on

Importing and displaying feeds in your WordPress themes is a great way to share additional content with your readers. Some good examples include:

  • Displaying your latest tweets, flickrs, or delicious saves
  • Displaying content from your other sites in your sidebar or footer
  • Providing a public link feed to which your readers may contribute or subscribe

Basically, anything that is available in any sort of feed format — RSS, XML, Atom, etc. — may be easily imported and displayed on your WordPress-powered site.

Prior to version 2.8, WordPress used Magpie and Snoopy functionality to make it easy to parse and display feeds. As described in my previous article on importing and displaying feeds in WordPress, including a feed using the built-in Magpie class is straightforward:

<?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://domain.tld/your-feed/', 7); ?>

This code example will import and display the feed of your choice in WordPress versions 2.7 and older. For versions 2.8 and 2.9 (and possibly beyond), WordPress has changed from Magpie and Snoopy to SimplePie and FeedCache for retrieval, parsing and automatic caching of feeds. This is a good thing, even though SimplePie ceased development shortly after it was adopted by WordPress. Hopefully someone will pick it up and run with it.

For now, we just want to use WordPress to display external feeds on our sites. To do this, WordPress gives us the new fetch_feed() function, which retrieves, parses, and caches any RSS feed, even those generated by your own installation of WordPress.

To use this new function, we begin with a compatibility check, just in case we’re running an older version of WordPress. If the function exists, we proceed by including the required file, feed.php. Then, once we have the required file, we specify the feed URI as the (only) parameter of the fetch_feed function:

<?php if(function_exists('fetch_feed')) {

	include_once(ABSPATH . WPINC . '/feed.php');  // include the required file
	$feed = fetch_feed('http://digwp.com/feed/'); // specify the source feed

} ?>

At this point, all of the XML data from our source feed is returned as a standard SimplePie object that we capture as a variable called “$feed”. With the feed data cached and ready, we may use a variety of SimplePie methods to manipulate and display the data according to our needs.

The first thing that we may want to do is specify the number of items to display:

$limit = $feed->get_item_quantity(7); // specify number of items

Here we are showing seven items, but you can choose any number you want. Next, we want to create an array containing all of our feed items so that we can then loop through it and display stuff like the title, the date, the post contents, and so on. Here is how we create our array of seven items:

$items = $feed->get_items(0, $limit); // create an array of items

Note that the first feed item is numbered zero (“0”) and the last feed item is specified by the previously declared $limit variable, so we know exactly how many items to include in the array.

At this point, we are ready to loop through the array and display data from each of our feed items. Before we do, however, we want to ensure that the feed isn’t empty. Once this is verified, we proceed to loop through each item and display its title, permalink URL, and post date:

<ul>

   <?php if ($limit == 0) { ?>

   <li>The feed is either empty or unavailable.</li>

   <?php } else { foreach ($items as $item) : ?>

   <li>
      <a href="<?php echo $item->get_permalink(); ?>" title="<?php echo $item->get_date('j F Y @ g:i a'); ?>">
         <?php echo $item->get_title(); ?>
      </a>
   </li>

   <?php endforeach; } ?>

</ul>

Not bad, but what about post content? In addition to the post title, date, and permalink, it’s useful to be able to display an actual snippet from each feed item. No problem, just add the following method to your feed loop:

<?php echo $item->get_description(); ?>

You can also display the title of the feed itself with this snippet:

<?php echo $feed->get_title(); ?>

Of course, there are many more types of data that may be extracted and displayed from your feed items. For more information, check the references at the end of this article.

For now, allow me to wrap things up by putting everything together into a nice, plug-&-play, copy-&-paste code snippet that is perfect for importing and displaying feed items on your WordPress-powered site:

<?php if(function_exists('fetch_feed')) {

	include_once(ABSPATH . WPINC . '/feed.php');               // include the required file
	$feed = fetch_feed('http://feeds.feedburner.com/jquery/'); // specify the source feed

	$limit = $feed->get_item_quantity(7); // specify number of items
	$items = $feed->get_items(0, $limit); // create an array of items

}
if ($limit == 0) echo '<div>The feed is either empty or unavailable.</div>';
else foreach ($items as $item) : ?>

<div>
	<a href="<?php echo $item->get_permalink(); ?>" 
	  title="<?php echo $item->get_date('j F Y @ g:i a'); ?>">
		<?php echo $item->get_title(); ?>
	</a>
</div>
<div>
	<?php echo substr($item->get_description(), 0, 200); ?> 
	<span>[...]</span>
</div>

<?php endforeach; ?>

This is the code that I use on my new site, jQuery Mix. It displays the following information:

  • Seven items from the jQuery.com feed
  • Permalink, date, and title for each item
  • First 200 characters of each item’s post content

This code snippet seems to work great and should be easy to customize to fit your specific needs. Check the docs for more information!

References

14 Responses

  1. Great, thanks for sharing. :)
    Wanted to use a plugin but now I will give this solution a shot to show my Google Reader recommendations on my blog.

  2. kylegetsspam November 23, 2009

    You forgot to put your RSS feed in the head part of your jQuery site. :P

    • Whereabouts? It’s there in the header with a blue icon.. is it not showing in your browser?

      • kylegetsspam November 23, 2009

        Nah, I saw that one just fine. But you don’t have it linked in via ‘rel = “alternative”‘ in your HTML header code, so the orange RSS icon doesn’t show up in Firefox’s address bar.

        It’s not a big deal; it’s just the first place I looked for it. :P

      • Ahh yes.. I totally forgot about that. Will get it added soon. Thanks for the heads up! :)

  3. Just a quick note:
    you do NOT have to specifically include ANY file for the fetching of feeds in WordPress 2.8+, thats done transparently.

    So, All you should do is this:

    if ( function_exists('fetch_feed') ) {
    $feed = fetch_feed('http://....');
    }

    wp-includes/feed.php is included automatically for you (to access the various feed template functions and fetch_feed()), And requires SimplePie if required to load the feed.

    • Okay thanks, that’s good to know. Definitely makes things a little cleaner. I’ll update the article after checking it out for myself.

  4. Montana Flynn November 24, 2009

    Wow, I had no idea it was that easy. I will use this to pull my latest tweet instead of JS. My concern is how often does it update?

    • You can specify any cache duration (in seconds) using this:

      $feed->set_cache_duration (43200);

      This will update the feed every 12 hours, but you could theoretically set it for any amount of time (just don’t go crazy!)

  5. I think my problem might be bigger but for all of the RSS feeds in my site I get this error.

    RSS Error: WP HTTP Error: couldn't connect to host

    This appears in the dashboard and I get similar errors when placing the snippet into the page. I developing this locally on MAMP.

  6. Sonic75 January 8, 2010

    Hi Jeff,
    Thank you SO MUCH for this! I am very excited reading this!

    My (probably) biggest problem, still? Probably lack of experience in coding.

    For reference: I followed the directions of “#4. Embed an RSS Reader” from another URL at http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/ . It worked perfectly. Except that when used it only shows titles/links. Not excerpts or actual content.

    So, searching around the internet for a better solution (that could show some content), I found your post here.

    The other post had code that made a function, that I pasted into my theme’s functions.php file. Then I used [function_name] in the post’s HTML to call it, and display the results on a blog page.

    I have eagerly looked at your plug-&-play code above– several times– but unfortunately I am not knowledgeable enough yet to know how to turn it into a function, etc., and access it from a blog post.

    How do I use this? How do I access it in the HTML of a blog post, to have the content show up on a blog page?

    Thank you for taking mercy on me and bringing the “plug-&-play” instructions down to an even simpler level !!

    • By default, WordPress won’t process PHP from within posts. For that you a need a plugin.. I think there’s one called “PHPexec”, but I’ve never used it and can’t recommend executing PHP from within post content. But it is an option if you aren’t comfortable placing the code into a template file.

  7. Tips Menulis Online February 11, 2010

    Very usefull. Thanks for sharing.

Comments are closed. Contact us with any critical information. Thank you!

Code is poetry