Style Your RSS Feeds in WordPress

RSS feeds are an important part of any WordPress blog. WordPress now comes with an RSS widget that allows you to display feeds in any widget area.

However, sometimes, you may want to display RSS feeds in the content area of your post. You may also want to change the structure and style of your feeds.

Here we consider how to render and style our own RSS feeds with PHP.

1. Get RSS Feed Items

First off we want to extract items from our RSS feed and render them as HTML elements. Luckily, WordPress already has some built-in functions that allow us to do this.

The function below accepts a feed URL and a list of arguments –

  • items_per_page – Number of RSS items to show per page. A <!nextpage–> delimiter will be added after every $items_per_page number of elements.
  • max_items -Maximum number of items to show from the RSS feed.
  • desc – Whether to show the description of the RSS feed items.
  • desc_length – The maximum length of each item description.
  • item_before,item_after – What HTML to add before and after each RSS item.
  • title_before,title_after – What HTML to add before and after each RSS item title.
  • desc_before,desc_after – What HTML to add before and after each RSS item description.
function render_rss( $url, 
		     $args = array(	"items_per_page" => 0, "max_items" => 0, 
					"desc" => false, "desc_length" => 150,
					"item_before" => '<div class="rss-item">', "item_after" => '</div>',
					"title_before" => '', "title_after" => '',
					"desc_before" => '', "desc_after" => '')) {
	extract($args);
	$str = '';

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

    // Figure out how many total items there are, but limit it to 5. 
   	if (!$max_items)
    	$max_items = $rss->get_item_quantity(); 
	if ($max_items <= 0) return ''; 
	if (!$items_per_page)
		$items_per_page = $max_items;   
	
    // Build an array of all the items, starting with element 0 (first element).
        $rss_items = $rss->get_items(0, $max_items); 

	$i = 0;$itemnum = 0;
	if (!is_array($rss_items) || empty($rss_items)) return $str; // no items
	else {
		// Loop through each feed item and display each item as a hyperlink.
		foreach ( $rss_items as $item ) : 
			$str .= "{$item_before}\n";
			$str .= "<a href='{$item->get_permalink()}' title='Posted {$item->get_date('j F Y | g:i a')}'>\n";
			$str .= "{$title_before}{$item->get_title()}{$title_after}</a>\n";
			
			if ($desc) { 
				$str .= $desc_before . shorten_description($item->get_description(),$desc_length) . $desc_after . "\n";
			}
			$str .= "{$item_after}\n"; 
			$i++;$itemnum++;
			if ($i >= $items_per_page) {
				if ($nextpage && ($itemnum < $max_items)) { $str .= "< !--nextpage-->"; $i = 0;}
				else break;
			}
	   endforeach; 
   }
   return $str;
}

Line 12 – Fetches items from an RSS feed and stores it in a SimplePie object. This may change in the future.
Lines 15-19 – Get the total number of items in the RSS feed. If the max_items argument is undefined, we set it to show all of the items in the feed. If the items_per_page argument is undefined, we set it to include all of the RSS items in a single page.
Line 22 – Build an array of all the items we want to show from the RSS feed.
Line 25 – If we fail to create any feed items, then return an empty string.
Lines 28-42 – Generate the proper HTML for each feed item based on our input arguments.
Line 44 – Return the generated HTML string.

2. Shorten RSS Item Description

Note that on line 34 we pass each RSS item description through a shorten_description function.

function shorten_description($result, $max_len) {
	$result = str_replace("\n", " ", $result);	
	$result = str_replace("\r", " ", $result);	
	if (strlen($result) > $max_len) {
		$end = strpos($result, ' ', $max_len);
		if ($end !== FALSE)
			return substr($result, 0, $end) . " [...]";
		else
			return substr($result, 0, $max_len) . " [...]";
	} else
		return $result;		
}

Lines 2-3 – Remove line feeds and line breaks from our item descriptions. This ensures that the item descriptions get rendered as a compact paragraph of text.
Lines 4-11 – Shorten our feed item descriptions. We ensure that the description is shortened on a word boundary i.e., we do not want to cut the text off in the middle of a word.

3. Link Our RSS Feed Functions to a WordPress Shortcode

Finally we may want to link our RSS feed functions to a WordPress shortcode. This will allow us to enter –

[rss url="http://feeds.feedburner.com/shiba-inu"]

And get the following result -

To add rss as a shortcode, we use the add_shortcode function.

function rss_shortcode($atts) {
	$atts = shortcode_atts(array(	"url" => '',
					"items_per_page" => 0, "max_items" => 0, 
					"desc" => false, "desc_length" => 150,
					"item_before" => '<div class="rss-item">', "item_after" => '</div>',
					"title_before" => '', "title_after" => '',
					"desc_before" => '', "desc_after" => '' ),
					$atts);
	return render_rss($atts);

}
add_shortcode('rss', 'rss_shortcode');

Since the default values are now handled by our rss_shortcode function we can simplify our render_rss function as follows -

function render_rss($atts) {
	extract($atts);
...
}

Note that the feed URL now gets passed as part of the $atts attribute array.

We Are Done!

All done! Here is another example rss feed from HubPages -

[rss url="http://hubpages.com/author/shibashake/best/?rss" title_before="<h4>" title_after="</h4>" desc="TRUE" max_items="5"]
    A feed could not be found at http://hubpages.com/author/shibashake/best/?rss. A feed with an invalid mime type may fall victim to this error, or SimplePie was unable to auto-discover it.. Use force_feed() if you are certain this URL is a real feed.

Related Articles

Comments

  1. Amba Junior says

    Thanks for this nice article and for the detailed explanation as well. How do I show featured images in the RSS feed

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>