A Better Way to Add RSS Feeds to Your WordPress Blog (Using Shortcode)

Some time back, I provided some very simple code that would render an RSS feed with shortcode. It was only this morning when I was writing a quick post that follows this one I’ll post soon that’ll show you how to include a Google Plus RSS feed into your WordPress post or page that I realised the previous method was a little archaic. In fact, the wp_rss function is now depreciated and replaced with fetch_feed. fetch_feed uses the SimplePie and FeedCache functionality for retrieval and parsing and automatic caching making it far easier and robust.

There are a number of shortcode attributes in the RSS code that makes it easy to customise your feed for the majority of purposes. For example, to include a list of recent posts, we’ll simply insert the shortcode of [rss feed="http://www.internoetics.com/feed/" size="3" excerpt="45"]. The feed defines the RSS to import, the size defines how many articles we’ll render on our screen and the excerpt determines how many words are in the post excerpt. The results is as follows:

  • Downtime… and our new server.

    15/04/2013
    8217;ve only just migrated over to our new dedicted server. Some services may experience problems in the next week or so while we code over to the new platform. Moving over to the new server gives us the opportunity to build the services (and ...
  • Display Testimonials or Quotes from an XML File with WordPress Shortcode

    30/03/2013
    finance website – managed by my brother, Jason – formerly used WordPress posts (in their own category) to showcase individual customer testimonials. The creation of the individual posts for each each testimonial was a grossly inefficient solution because a visitor would have to ...
  • Happy New Year

    28/03/2013
    ow, it’s a little late, right? Well, it’s the first time I’ve posted since November 28 last year. Quite a lot has happened over the last 4 months that precluded me from investing time into my arsenal of websites. My aviation career, consulting ...
  •  

    The Function

    All available attributes are as follows:

    size = Number of posts to Render
    excerpt = Number of words in the excerpt
    feed = URL of the RSS feed to import
    date = Display date? true of false.
    heading = Heading tags. Eg, H4, H3, strong, em, u
    list = Display as list? true or false.
    cache = Time to cache (3600 = 1 hour)

    You will need to copy the following code into your theme’s functions.php file or add it into your shortcode plugin. As always, it’s easier and safer to copy the code from the zip file below; copying is prone to errors.

    // Simple Pie RSS Shortcode
    function simplepierss($atts) {
      extract(shortcode_atts(array(
      'size' => '5',
      'excerpt' => '30',
      'feed' => 'http://www.internoetics.com/feed/',
      'date' => 'true',
      'heading' => 'h4',
      'list' => 'true',
      'cache' => '1400'
      ), $atts));
    
    // SimplePie RSS parsing engine
      include_once ABSPATH . WPINC . '/feed.php';
    
        // Set the cache time for SimplePie
        add_filter( 'wp_feed_cache_transient_lifetime', create_function( '$a', "$cache;" ) );
    
    		// Build the SimplePie object
    		$rss = fetch_feed($feed);
    
    		// Check for errors in the RSS XML
    		if (!is_wp_error( $rss ) ) {
    
    			$maxitems = $rss->get_item_quantity($size);
    			$rss_items = $rss->get_items(0, $maxitems);
    
    			$i = 0;
    			$total_entries = count($rss_items);
    
    			if ($list == true) $html = "<ul class='feedlist'>";
    
    			foreach ($rss_items as $item) {
    				$i++;
    
    				if( $total_entries == $i ) {
    					$last = " class='last'";
    				} else {
    					$last = "";
    				}
    
    				$title = $item->get_title();
    				$link = $item->get_permalink();
    				$desc = $item->get_description();
    				$date_posted = $item->get_date('d/m/Y');
    
        $desc =wp_kses(trim($desc),array());
        $desc = apply_filters('the_excerpt', $desc);
    
        $desc = strip_tags($desc,"");
        $excerpt_length = $excerpt;
        $words = explode(' ', $desc, $excerpt_length + 1);
        if(count($words) > $excerpt_length) :
           array_pop($words);
           array_push($words, '...');
           $desc = implode(' ', $words);
        endif;
        $desc = trim($desc);
    
        while(strpos($desc, '  ') !== false)
                        $desc = str_replace('  ', ' ', $desc);
        $desc = substr(($desc),10);
    
    	if ($list == "true") {
    	   // Output
    	   $html .= "<li id='post-$i'$last>";
    	   $html .= "<$heading><a href='$link'>$title</a></$heading>";
    	   if( $date == "true" ) $html .= "<span class='date'>$date_posted</span>";
    	   $html .= "<div class='rss-entry'>$desc</a></div>";
    	   $html .= "</li>";
    
    	   } elseif ($list == "false") {
    
    	   $html .= "<$heading><a href='$link'>$title</a></$heading>";
    	   if( $date == "true" ) $html .= "<span class='date'>$date_posted</span>";
    	   $html .= "<div class='rss-entry'>$desc</a></div>";
    	     }	
    	   }
    	   if ($list === true) $html .= "</ul>";
    	   } else {
    	   $html = "Error occurred while parsing your RSS feed. Visit the website at $feed.";
    	}
    
    return $html;
    }
    add_shortcode("rss", "simplepierss");

    RSS Feeds in a Sidebar

    Of course, if you haven’t already, the following code must be in your functions.php file to support shortcode in widgets: add_filter('widget_text', 'do_shortcode');.

    If you wanted posts in your sidebar, you could use something like the following: [rss feed="http://www.internoetics.com/feed/" size="5" excerpt="25" date="false" heading="strong" list="false"]. Styling for links is based on your primary CSS file. My links are underlined in content, but not in the sidebar.


    Something like [rss feed="http://www.internoetics.com/feed/" size="5" excerpt="0" date="true" heading="text" list="true"] would return 5 articles as a list with no excerpt.


    As I said, this article is a companion to the post that follows in a few days soon that’ll show you how to insert your latest (public) Google Plus posts to your WordPress blog.

    You can read more about fetch_feed here and Simple Pie here.

    Let me know if you have problems.

    First Name:
    Your Email Address:
     




    Download: Simple-pie-rss-shortcode
    Description: RSS Shortcode. Using Simple Pie.
    Author:Marty
    Category: PHP code
    Date: May 2, 2012



    If you liked this article, you may also like:

    1. Add Your Latest Google Plus Post(s) to Your WordPress Blog (or Generate a Google+ RSS Feed)
    2. Exclude posts from WordPress blog or RSS feed based on a tag
    3. Generate Random WordPress Posts with Shortcode
    4. [Shortcode] Easily post an aviation TAF report into your WordPress post or page with shortcode
    5. [Shortcode] Include an RSS feed in a post or page with shortcode
About Marty

is a passionate web developer from Sydney, Australia. He owns about 600 websites and makes a healthy living from working the web. As a day job, he works as a pilot for an international airline. Follow Marty on Twitter or Google+.

Comments

  1. Josef Ulander says:

    Thanks for the code! How do I get a “read more” link after the excerpt?

    J

    • Marty says:

      Hi Josef. Use:

       <a href='$link'>Read more...</a> 
      

      … after each occurence of $desc link (on line 69 and 76).

      Line 69, for example, will look like:

      $html .= "<div class='rss-entry'>$desc - <a href='$link'>Read more...</a></div>";

Trackbacks

  1. [...] May (it’s been sitting in drafts since then)… and the intent was that it would follow this post (titled ‘A Better Way to Add RSS Feeds to Your WordPress Blog Using Shortcode‘). You [...]

Speak Your Mind

*