How to Get those Handy Social Network Statistics Counters

Most sites nowadays have a little collection of icons and numbers in a section of their webpage. The purpose of this jumble of pictures and text? To show how popular the site is on social networks. Well now you must be thinking, “Cool! How can I do that?” After reading this article, not only will you have those handy, dandy counters on your site, but you’ll also be able to blend the counters into the typography of your site, instead of using the standard buttons.

Preparation

If you want to get a counter for an RSS feed and are using FeedBurner, make sure to log in and activate the Awareness API in the Publicize settings section.
WordPress uses an API called the transients API to store information for a limited time and refresh it when needed. We’re going to be putting the transient function and the code for each service in two different functions.

The Transient Function

The first thing you’re going need to do is paste the following code into your theme’s functions.php file.

/**
 * 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;
}

For a full introduction to Transients, you can check out this site.

What does all this code actually do?

The pbd_get_transient() takes one parameter; the name of the service.

Then it sets the cache time. It then checks on line 14 if there’s a value for tweet data already saved. If so, it’s just returned.

Then on line 17, it takes the name passed to the function and creates a function name based off that, in this case ‘pbd_get_twitter’. If the function exists it will be called and the value will be saved. Otherwise it will just say “Function not found.”

Line 25 checks the value received. It should be positive. If it’s negative, the service probably didn’t respond so the last number stored is used.

Line 29 saves the new transient value. Line 30 saves it again with a longer cache time to serve as a backup.

How to Get the Values

Let’s do Facebook first. Paste the following snippet into 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']);
}

Replace ‘problogdesign’ on line 5 with whatever the name of your page is. Line 7 checks to make sure that line 5 retrieved the needed file. If it didn’t, the first function we made knows to use the backup value. Line 10 converts the JSON document into a regular PHP array. Line 12 picks out the fan count.

The procedure for Twitter is pretty much the same thing:

/**
 * 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']);
}

All that’s really changed is some of the names. Make sure to replace ‘problogdesign’ with your Twitter username.

FeedBurner is also very similar, but it uses XML instead of JSON.

/**
 * 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']);
}

It starts out with retrieving the file like before. On line 10, however, PHP’s SimpleXML extension is used to get the necessary data. Make sure to switch ‘problogdesign’ with your feed name.

Display the Counts

Find where you want your counters (e.g. sidebar.php) and insert the following:

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

pbd_get_transient returns the value and it’s wrapped in the number_format so that if it gets into the thousands, it’ll add commas.

For Facebook insert:

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

For Twitter insert:

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

You can also display a combined total of your fans with the following snippet (inserted where you want it displayed):

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

(Info from: Pro Blog Design)