Show RSS feeds inside WordPress pages through PHP

Here is an another addition to my WordPress as CMS series, I was working for a client and there was a need that I fetch RSS feeds and then output the items in a certain fashion.

I was aware of the wp_rss() function but when I checked it on Codex, I found out that the function has been deprecated and the Codex suggests to use fetch_feed() function instead. Using feed_fetch() function also caches the feeds fetched so that successive loads can be generated faster by taking advantage of the cache.

Without any further delay, here is how I used it to parse the feeds and then displayed the needy items in a list →


// Get RSS Feed(s)
include_once(ABSPATH . WPINC . '/feed.php');

// Get a SimplePie feed object from the specified feed source.
$rss = fetch_feed('');

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);

echo '<ul>';

	if ($maxitems == 0)
		echo '<li>No items.</li>';
		foreach ( $rss_items as $item ) 
			// echo '<pre>'; print_r($item); echo '</pre>'; break;
			echo '<li>';
			echo $item->get_date('H:i');
			echo '<br /><a href="'.$item->get_permalink().'">'.$item->get_title().'</a>';
			echo '</li>';
echo '<ul>';


Here we include the feed.php from the includes folder as it is necessary, then we call feed_fetch() function by passing the feed url as argument and it returns a object containing our feed items.

We check if the object was created correctly with the help of is_wp_error() function. In case some error has occurred then the error code will be stored in the variable instead and by this method we can check for errors.

We limit the maximum number of items we want and then store them in a different variable which can be iterated via foreach loop.
Here is a list of what all you can extract out of your feeds – SimplePie Documentation

You can style it further by adding CSS classes and then style it via CSS in your theme stylesheet. If you need any help, then leave a comment here and I will try to help ๐Ÿ™‚


3 responses to “Show RSS feeds inside WordPress pages through PHP”

  1. […] This post was mentioned on Twitter by Ashfame, KarShan Media. KarShan Media said: RT @ashfame: Show RSS feeds inside WordPress pages through PHP […]

  2. Thanks this was most helpful for my blog. Great information you have here.

    1. Glad that you like it ๐Ÿ™‚