@dangayle

The correct way to import feeds into WordPress using fetch_feed()

Feeds are a wonderful thing. I love my Google reader, because I can keep up to date with all the new web designery goodness available on teh intarwebs.

Feeds are also useful as content sources for people too lazy to write their own stuff. I know, I know, it sounds awful to say it that way, but that’s the reality of it all. If you had awesome content bursting out of your own ears, you’d never need to pull in someone else’s finely wrought content.

Back to the point, this is how a trillion how-to tutorials on the web teach you to pull a feed into WordPress, serverside:

<?php
include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://feeds.feedburner.com/wprecipes', 3);
?>

The problem with that method is that that it is deprecated. From the WordPress Codex:

This function has been deprecated. That means it has been replaced by a new function or is no longer supported, and may be removed from future versions. All code that uses this function should be converted to use its replacement if one exists. See also wp-includes/deprecated.php. WP_RSS Function Reference

That function does exist, but you’d never know it, if judging by the lack of “airtime” it gets on the tutorial sites.

Here’s the proper way to retrieve a feed into WP, in a useful little mini-feed-loop that I put together:

<?php
include_once(ABSPATH . WPINC . '/rss.php');
$feed = 'http://example.com/feed/';
$rss = fetch_feed($feed);
if (!is_wp_error( $rss ) ) :
    $maxitems = $rss->get_item_quantity(3);
    $rss_items = $rss->get_items(0, $maxitems);
    if ($rss_items):
        echo "<ul>\n";
        foreach ( $rss_items as $item ) :
            echo '<li>';
            echo '<a href="' . $item->get_permalink() . '">' . $item->get_title() . "</a>\n";
            echo '<p>' . $item->get_description() . "</li>\n";
        endforeach;
        echo "</ul>\n";
    endif;
endif;
?>

Basically, fetch_feed() uses SimplePie to do in a “way mo betta way” what wp_rss() uses magpieRSS and Snoopy HTTP to do. SimplePie’s documentation and ease of use is awesome, even if the functionality to retrieve the feed looks more complicated on this end.

Using WP’s fetch_feed()/SimplePie functionality, you have a lot more control over how you display the feed. I just showed an example pulling the link, but it’s really easy to pull any/all of the data out of any RSS feed, something that you couldn’t do as easily with the old busted style.