Twitter, Facebook, RSS Counts

You will have seen blogs showcase their Twitter, Facebook, and RSS counts with typography. With these numbers in plain text, you can style them into your website far more effectively than if you were to use the old-fashioned “chicklets.”

Twitter and Facebook make this easy, but you’ll need to take an extra step with FeedBurner first. Log in, then click Publicize > Awareness API, and click activate.

All set? Then let’s get started!

Chicklets(And yes, I know we’re still using the chicklets here, but they’ll be gone for good in a few more days so just ignore that for now!)

Planning Our Script

When we get a number from one of these services, we will need to save it to our server.

This is so we can retrieve it from there without having to go out to the service again (Otherwise, the service might cut us off for requesting it too often, and it’s faster this way too).

Regular readers will know where this is heading; the transients API. Transients are WordPress’ way of letting you store information for a limited time (And refreshing it later when you need).

In previous posts where we have used transients though, we have merged the transient code with the code to get our information. This time, we are going to split the two up (So we don’t end up re-writing the transient code each time).

We will have one function that stores/retrieves a transient, and then a function for each service to get the number we need.

1 – Our Transient Function

For a full introduction to transients, you can read our Transients API tutorial. I’ll summarize what the following code is doing afterwards though, so don’t worry if you don’t follow it right away.

Open up your theme’s functions.php file, and paste the following between the opening and closing tags:

/**
 * Retrieve transient value.
 *
 * Returns a transient value, or updates that transient if it has expired.
 *
 * @param $name String. Name of the service, e.g. twitter
 * @return String. New transient value.
 */
function pbd_get_transient($name = 'twitter') {
	$transName = "pbd-transient-$name"; // Name of value in database.
	$cacheTime = 8; // Time in hours between updates.
 
	// Do we already have saved tweet data? If not, lets get it.
	if(false === ($trans = get_transient($transName) ) ) :
 
		// Make the name of the function that gets our transient value.
		$func = "pbd_get_$name";
		if(function_exists($func) ) {
			$trans = $func();
		} else {
			$trans = 'Function not found.';
		}
 
		// Did we get a positive number? If not, use the old value.
		if(!absint($trans) > 0)
			$trans = get_transient($transName . '-old');
 
		// Save our new transient, plus save it in the longer "backup" transient.
		set_transient($transName, $trans, 60 * 60 * $cacheTime);
		set_transient($transName.'-old', $trans, 3 * 60 * 60 * $cacheTime);
	endif;
 
	return $trans;
}

Now let’s break down what this is doing:

  • The pbd_get_transient() expects 1 parameter, the name which makes our transient and “get” function names (In our case, ‘twitter’, ‘facebook’, or ‘rss’, though you could use it for anything else as well).
  • We set a cache time (8 hours), and on line 14, we check if a value is already saved. If it is, we just return it.
  • Line 17 is where it gets interesting. We take the name that was passed to the function, and build a function name from it, e.g. ‘twitter’ becomes ‘pbd_get_twitter’. If the function pbd_get_twitter() exists, we will then call it and save the value it gives (Lines 18 and 19).
  • On line 25, we check the value we have. It should be a positive number. If it isn’t, odds are that the service didn’t respond to us, so we will use the value we saved the last time.
  • On line 29, we save the new transient value, and save it again on line 30 with a longer time limit (So we can use it as a backup if we need to).

And that’s our caching taken care of. We can now re-use this same function for each of our services. Much better, isn’t it?

2 – Get the Numbers

The next step is to go to each service and get the value we want. Thankfully, they’ve all made it very easy with their APIs.

Let’s start with Facebook, add the following to your functions.php file:

/**
 * Get Facebook Page Fan Count.
 */
function pbd_get_facebook() {
	$json = wp_remote_get("http://graph.facebook.com/problogdesign");
 
	if(is_wp_error($json))
		return false;
 
	$fbData = json_decode($json['body'], true);
 
	return intval($fbData['likes']);
}

On line 5, you would replace ‘problogdesign’ with your Facebook Page’s name of course (You can load the URL directly in your browser to make sure you have it right, e.g. click here).

With line 5, WordPress will grab the file. We check that it did this successfully on line 7 (If it didn’t, then our previous function will know to use its backup value).

With line 10, we convert the JSON document we downloaded into a regular PHP array, and last of all, we pick out just the fan count and return it (Making sure it’s an integer).

Twitter is almost identical:

/**
 * Get Twitter follower count.
 *
 * @return Int. Twitter follower number.
 */
function pbd_get_twitter() {
 
	$json = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name=problogdesign");
 
	if(is_wp_error($json))
		return false;
 
	$twitterData = json_decode($json['body'], true);
 
	return intval($twitterData['followers_count']);
}

As you can see, all we have done is changed some of the names. The method is identical, just replace the problogdesign part with your Twitter username.

Now, let’s do FeedBurner. The method here is similar, but instead of JSON, FeedBurner only offers an XML format:

/**
 * Get RSS subscriber count from FeedBurner.
 *
 * @return Int. RSS follower number.
 */
function pbd_get_rss() {
	$xml = wp_remote_get('http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=problogdesign');
 
	if(is_wp_error($xml))
		return false;
 
	$sxe = new SimpleXMLElement($xml['body']);
 
	return intval($sxe->feed->entry['circulation']);
}

We start out the same, by grabbing a file from the service (And again, replace the problogdesign part with the name of your feed).

The difference is on line 10, where we use PHP’s SimpleXML extension to get the data we need. And once again, we pick out only the subscriber number to return, and make sure it’s an integer.

3 – Display the Numbers

You’ve now written the 4 functions to get each number and save it. All that’s left to do is print it out on your site.

Browse to wherever you want to list your numbers (e.g. sidebar.php), and insert the following:

<?php echo number_format(pbd_get_transient('rss') ); ?>

We call pbd_get_transient(‘rss’) to return the value, and I’ve wrapped it in number_format() so that commas will be added if the number is in the thousands.

Similarly, for Facebook:

<?php echo number_format(pbd_get_transient('facebook') ); ?>

And Twitter:

<?php echo number_format(pbd_get_transient('twitter') ); ?>

4 – Display a Combined Total

We could have applied number_format() earlier on, before we saved the values. The reason to store the plain integers instead is so you can add the 3 numbers together and display a combined total, if you like.

<?php
$sum = pbd_get_transient('rss') + pbd_get_transient('twitter') + pbd_get_transient('facebook');
echo $sum;
?>

And that’s us all done! Now you (and I) have no more excuses for using the buttons they give us. Instead, just well designed typography.

Update (29th July ’11) – Thanks to Bryan Hadaway for pointing out ‘&gt;’s in the code!

Enjoy this post? You should follow me on Twitter!