How To: Show Off Your Social Counters in WordPress

You know it’s all about social these days, and this post is about showing off how social you are on your WordPress website. I’m sure you’re using tonnes of social networks and all of them have friends, followers, fans and subscribers metrics, but let’s start from simple: Twitter, Facebook and RSS.

We’ll write code in this post, and you may ask me why. Of course there are loads of copy-paste javascript widgets available, but the first problem I encountered with those is they’re all different! What we’re going to do here is grab the numbers on the server, so then you’ll be able to display them however you like, with your own icons and captions.

I wrote a couple of posts on this topic last year:

We’ll be using some of those snippets in our code today, together with a few additions for Twitter followers count and RSS subscribers too. We will also adapt these to WordPress. Okay, enough talk, let’s get to the coding!


Icons Credit: Drink Web 2.0 by Bruno Maia

Twitter Followers Count

This one’s quite simple, since the Twitter API allows a non-authenticated call to public users. Assuming we’ve got JSON functions available (PHP5 or JSON Services in PHP4):

public function get_twitter_followers_count( $screen_name ) {
	if ( false === ( $followers = get_transient( 'twitter-followers-count' ) ) ) {
		$response = wp_remote_get( "http://api.twitter.com/1/users/show.json?screen_name={$screen_name}" );

		if ( is_wp_error( $response ) ) {
			$followers = 91;
		} else {
			$json = json_decode( wp_remote_retrieve_body( $response ) );
			$followers = $json->followers_count;
		}
		set_transient( 'twitter-followers-count', $followers, 60*60*24 );
	}
	return $followers;
}

As you can see I’m using the Transients API to cache the followers count for 24 hours, this reduced the load on the hosting server and serves pages faster. I’ll be using transients for Facebook fans and RSS subscribers too.

Line 5 might seem a little strange, we’re explicitly setting followers to 91. We do that when there’s an error with the API call so that we don’t show off a zero-count. You can go forward and extend it to double-cache values with a get_option and set_option call so that 91 is actually a figure retrieved from Twitter API and not hard-coded. But that’s extra, I’m fine with 91 ;)

The rest seems straightforward — we parse the response using json_decode and grab the followers count. If you’re into grabbing something else, go ahead and inspect the $json object using print_r, there’s so much interesting stuff there ;)

When the followers count is in our hands, we set a transient for it, so that next time it is served from cache, and finally return the count. Simple as that ;) The usage is easy — just pass a screen name to the function and you’ll get the results, as long as it is not a protected profile.

RSS Subscribers Count

As I already mentioned, transients will be used here as well, same method. Additionally we’ll be using Feedburner’s Awareness API. In order for that to work you’ll have to have your RSS feed setup with Feedburner and the Awareness API activated. Take a look at the “AwAPI Activation and the FeedCount Chicklet” section following the link above.

public function get_rss_subscribers_count($feed_url) {
	if (false === ($subscribers = get_transient('rss-subscribers-count'))) {
		$feed_url = urlencode($feed_url);
		$response = wp_remote_get("http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri={$feed_url}&dates=" . date('Y-m-d', strtotime('-2 days', time())));

		if (is_wp_error($response)) {
			$subscribers = 97;
		} else {
			$body = wp_remote_retrieve_body($response);
			$xml = new SimpleXMLElement($body);

			$status = $xml->attributes();

			if ($status == 'ok') {
				$subscribers = $xml->feed->entry->attributes()->circulation;
			} else {
				$subscribers = 98;
			}
		}

		$subscribers = (int) $subscribers;
		set_transient('rss-subscribers-count', $subscribers, 60*60*24);
	}
	return $subscribers;
}

As you can see, we’re fetching the RSS feed data using the feed URL via an HTTP request to the Feedburner API. The Awareness API returns an XML object, which is then parsed using the Simple XML methods. The circulation attribute is the one we’re looking for — it indicates the approximate subscribers count.

Again, I’ve hard-coded the 98 figure there for fallback purposes, you might want to extend it. The date magic simply asks Feedburner for stats of two days ago, since it sometimes yields 0 for “today” and “yesterday”. Could be changed according to your Feedburner stats if that matters.

Finally, we’ve set the transient and returned the subscribers count, voila. Usage: pass on your Feedburner feed URL to get_rss_subscribers_count(), an integer is returned.

Facebook Fans Count

Last but definitely not least — Facebook. We’ll use the Facebook PHP SDK, I’m using version 2.1.2 which seems to be the latest stable at the time of writing. We’ll be using the Graph API way, so no more FQL queries please. Here’s the code:

public function get_facebook_fans_count($page_name) {
	if (false === ($fans = get_transient('facebook-fan-count'))) {
		require_once("facebook/facebook.php");
		$facebook = new Facebook(array(
			'appId' => 'your-application-id',
			'secret' => 'your-application-secret'
		));

		$graph_obj = $facebook->api("/{$page_name}");
		$fans = $graph_obj['fan_count'];

		set_transient('facebook-fan-count', $fans, 60*60*24);
	}
	return $fans;
}

Note, that unlike the old-fashioned way, the Graph API uses your application ID, not your API key. You can obtain these when registering a new application at the Facebook Developers page. There’s a button that says “Set Up New App” which takes you through the rest of the process.

So once your app is in place, credentials are fine and the connection is good, we use facebook’s api method to request for a page name. Try “mashable” for example.

The returned Graph object contains quite a lot of stuff, including the number of fans. Use print_r on $graph_obj to learn more. So the fan count is obtained, a transient is saved, and the number is returned.

Conclusion

Note that if you’re going to use these for different profiles, you’ll have to change the names of your transients to include that data, otherwise there will only be one cache. I kept the code as simple as possible here, but I’ve illustrated the extra stuff in the final source that I did. I also wrapped these up in a single class called $social, I know it’s too generic for WordPress, but I’m not writing a plugin out of this (yet). The source could be downloaded right here. Feel free to use and extend the code with your own methods for other social networks and services.

Okay well, thank you so much for reading and retweeting this, oh and by the way…

Question: what other 3-5 services would you like to get your numbers from?

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

12 comments

  • Thanks for the tutorial. Mailchimp would be a great one. They have a simple merge tag that will work inside of emails but their chiclet's are horrible

    • Sweet tutorial. I was going to suggest Mailchimp as well, seeing as how they don't send subscriber counts back to Feedburner.

  • Hmmm, possible problems being 1) I tweet more about stuff than photography and don't feel my site should have its own account and 2) what if someone follows you on twitter and facebook?

  • Hi, thank you for this tutoral but could you explain it more precisely please?
    I mean where to put this code?

    I have downloaded the file facebook.php (v 2.1.2) and have uploaded it in my wordpress theme folder under "wp-content/themes/my-theme/facebook.php"… where do I have to put the 15 lines of code for the facebook fancount you've posted here and how do I show the counter on my site?

    Thank you very much!

    • Mike, the code should live inside your functions.php file or you might want to wrap it up into a plugin. My <code>require_once</code> assumes you've got facebook.php inside a <code>facebook</code> directory in your theme. If you've got yours in your theme root just remove the dir from the function, should be fine. Turn <code>WP_DEBUG</code> on to track down errors ;)

      Good luck!

  • Hi! Wow; this is such a helpful piece of code! I didn't even know about transients before I read this. Quite the eye-opener.

    Now, as of this week, Facebook has moved to PHP SDK v3.0 (supporting v2 oAuth). I *assume* this merely requires the addition of authentication by calling $facebook->getUser(), but I'm not sure.

    In any case, I keep ending up NOT getting a user, and thus no graph object. Perhaps you could update this wonderful example?

    Also: I am very new to Facebook apps and I'm currently developing on localhost. I believe this is causing my authentication to fail, even though my app's "Site URL" is set to localhost. Do you know of any other fields in the app config that should be entered to allow a connection from localhost?

    Thanks so much!

    • Would be great if you pasted your code and print_r the response you get back to some pastebin, we might be able to figure this out ;)

  • Oh, one more thing: v2 oAuth sets a cookie by default, causing in a "Headers already sent" error. You could either move the number fetching to the functions.php or disable the Facebook cookie using:

    $facebook = new Facebook(array('appId' => '…', 'secret' => '…', 'cookie' => false));