Mr Speaker


Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 24

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 27

Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 29

Convert WordPress fetch_rss to fetch_feed

I realised that I wasn't properly handling the return value on a feed I was grabbing to display the "Spiffy things from the Internet" section of the blog. I went to WordPress to look up the fetch_rss API details, only to find that it had been deprecated in WordPress 2.8.something. Being the ever-vigilant beacon of vigilance, I decided to covert my feed-fetching to feed_fetch. Here's what I had to do.

There's not much to it, for the simple stuff. But SimplePie (the rss class that feed_fetch uses) has a LOT of advanced options that you should check out. For a basic feed we just need to update a couple of calls.

From the old code:

<ul>
<?php
include_once(ABSPATH . WPINC . '/rss.php');
$rss = fetch_feed('http://feed_url_here');
foreach ( $rss->items as $item ) : 
?>
	<li>
		<a href='<?php echo $item['link']; ?>'>
			<?php echo $item['title']; ?>
		</a>
		<?php echo $item['summary']; ?>
	</li>
<?php endforeach; ?>
</ul>

To the new code:

<ul>
<?php 
$rss = fetch_feed('http://feed_url_here'');
foreach ( $rss->get_items() as $item ) : 
?>
	<li>
		<a href='<?php echo $item->get_permalink(); ?>'>
			<?php echo $item->get_title(); ?>
		</a>
		<?php echo $item->get_description(); ?>
	</li>
<?php endforeach; ?>
</ul>

All we have done is moved from array indexes ($item['title']) to class getters ($item->get_title()). And we're away! If you hunt through the SimplePie docs, you'll notice that there are options to set cache files, timeout times, content types etc... But don't worry about these: WordPress handles it in the fetch_feed wrapper it provides.


Warning: count(): Parameter must be an array or an object that implements Countable in /home/mrspeak/public_html/wp-content/themes/stuartspeaker/functions.php on line 33

3 Comments

  1. Thanks for the help, although I believe you forgot the “echo” in getting the permalink.

    Friday, October 23, 2009 at 12:46 am | Permalink
  2. Thanks Mike… updated.

    Friday, October 23, 2009 at 6:49 am | Permalink
  3. It seams fetch_feed() in old code should be fetch_rss().

    Thursday, May 17, 2012 at 4:41 am | Permalink
Captcha! Please type 'radical' here: *
How did you find this thingo? *