WordPress: get the FeedBurner subscriber count the right way

WordPress: get the FeedBurner subscriber count the right way

How to get the actual number of our FeedBurner subscribers by using the WordPress Transient APIs.

The FeedBurner Awareness APIs don't work as many developers think they do. Simply put, all the data related to our feeds are generated according to the moment when a request is made. For example, if you get 0 as the total number of your subscribers, it doesn't mean that the feed is not working. It simply means that when you've performed your request, say at July 29, 2012 12:10 PM, nobody has subscribed to your feed. But if you use the dates URL parameter and get back of a couple of days, you'll magically get all your subscribers. In this article we'll see how to display our subscribers on WordPress by using the Transient APIs.

We can use the following code:

function feedburner_subscribers($id = 'blogspot/onwebdev') {

        $count = get_transient('feed_count');
        if ($count != false) { 
        	return $count;
        }
		$count = 0;
		$today = strftime('%Y-%m-%d', time());
		$past_time = strtotime('-2 day');
		$past = strftime('%Y-%m-%d', $past_time);
		
        $data  = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=' . $id . '&dates=' . $past . ',' . $today);
   		if (is_wp_error($data)) {
        	return 'Error';
   		} else {
			$body = wp_remote_retrieve_body($data);
			$xml = new SimpleXMLElement($body);
			$status = $xml->attributes();
			
			if ($status == 'ok') {
				$count = $xml->feed->entry->attributes()->circulation;
			} else {
				$count = 300; // fallback
			}
   		}
		set_transient('feed_count', $count, 60*60*24); // 24 hours
		return $count;
}

As you can see, we're using the WordPress Transient APIs to cache the total number of our feed subscribers for 24 hours. Once this time span has expired, the above function will perform the request again.

Note also that we've used the dates parameter with two dates: the former is a date in the past (two days ago) while the latter is the current date.

We've used this URL parameter just to make sure that the FeedBurner API's won't return 0. To use this function, simply specify your FeedBurner ID as the sole function's parameter:

<p><?php echo feedburner_subscribers('yourID');?></p>