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?

Facebook Fans Count Using Python and the Graph API

I noticed some peeps struggling to show off their Facebook fans count on their websites using the Facebook API. I’ve shown before on how to do it in PHP, and this quick post is about Python. Honestly, you’ll laugh as soon as you read the following three lines of code:

import facebook
graph = facebook.GraphAPI()
print "Mashable has %s fans" % graph.get_object('/mashable')['fan_count']

Yeah, and that is one more reason to love Facebook. Now, you might be wondering where I got that Facebook module I imported? It’s called the Facebook Python SDK, it’s free and open source, hosted at Github and seems to be official.

There’s other info about public objects available via that method as well, you can get a full list by printing the whole object which is a dictionary:

print graph.get_object('/mashable')

Don’t forget to cache objects since you wouldn’t like to fire requests at Facebook every time your page loads up. If you’re thinking about other Graph API methods, make sure you read the Authorization section in the Graph API Overview since you’ll need OAuth tokens to make requests.

Heh, maybe I should continue this series of posts for a dozen of other languages too? ;) Thanks for sharing!

WordPress and Magic Quotes

This is crazy, and based on a post called WordPress and PHP magic quotes: you want to run me crazy! by Stefano Lissa. I’m writing a plugin prototype for WordPress that uses the new Facebook Graph API to post stuff to my wall on Facebook (upcoming blog post). The original Facebook PHP SDK comes in very handy when working with the Facebook API, and I had quite some fun using it, but..

I’ve been trying to figure this out for hours! I had code working outside WordPress and once I pumped it into a plugin it suddenly stopped authorizing me. I had to dig through the facebook.php code to figure out what’s happening, and here it is. The getSession() method uses the get_magic_quotes_gpc function and strips the slashes from the $_COOKIE superglobal if it’s switched on. Of course, that’s the correct logic supporting both php 5 and php 6, but not WordPress.

I looked through the latest (3.0.1) WordPress core code and was quite surprised to see a function called wp_magic_quotes(). Oh my god, thought I! Commented as: Add magic quotes and set up $_REQUEST ( $_GET + $_POST ).

What the hell is that? Okay, let’s see:

$_GET = add_magic_quotes($_GET);
$_POST = add_magic_quotes($_POST);
$_COOKIE = add_magic_quotes($_COOKIE);
$_SERVER = add_magic_quotes($_SERVER);

How does that sound? So all my apps, plugins, external libraries working with server variables (like Facebook does with cookies) are not allowed to use the magic quotes function? This means that working with WordPress, we must initially assume that all these are quoted, no matter what the php settings are. I don’t even know what question to ask here, perhaps: Is this the way things are done? Why?

To be honest this is getting me a little frustrated. Not by the fact that they’re slashing the whole input (although I don’t see a reason to) but, heh, I’ve been coding based on WordPress for over two years now, and never came across anything like this. Did I miss something in the Getting Started guide? ;) Anyways, the easiest way to get this working is to replace your get_matic_quotes_gpc function with 1, which says it is always switched on.

Eh, Monday morning disappointment ;) Cheers, and thanks for sharing the post!

Counting Facebook Fans in PHP: The Graph API Way

In a previous blog post called How to Count Facebook Fans in PHP I’ve shown a code snippet of how to count the number of fans on a fan page using PHP. Times have changed, the Graph API has been introduced, and due to some responses I introduce here the new way of retrieving your fans count using the new Graph API and php.

Before you copy and paste, flush my comments with ‘my code is not working’ posts, I’d like to get your attention to versioning of the Facebook PHP SDK which we’ve been using all this time. The SDK has changed and of course the old method doesn’t work with the new SDK which is mostly tuned to Graph API, therefore, my previous code still works on a dozen on websites, because I have the old SDK installed back there. So please, be careful to what you download and use, read release notes and change logs, it will save you hours of googling.

The following snippet is based on the Facebook PHP SDK version 2.1.1 (use the Switch Tags option on github to browse through different tags). So get a fresh copy of facebook.php and have it somewhere nearby.

Unlike the old FBQL way, the new Graph API is much easier to work with, and retrieving the fans count is literally two lines of code (initialization doesn’t count). Here’s the snippet to retrieve the fans count for Mashable (don’t forget to replace your application ID and API secret):

require('facebook.php');

$facebook = new Facebook(array(
	'appId' => 'your-app-id',
	'secret' => 'your-api-secret',
));

$mashable = $facebook->api('/mashable');
echo 'Mashable has ' . $mashable['fan_count'] . ' fans';

Easy as that! I was also surprised to see that the Graph API is doing so well. Yeah, the documentation is not very rich, but whenever you need to retrieve something from Facebook, you can always print_r the results, which gives you the full picture. Sending data into Facebook is a little trickier and I’ll show you how in a later blog post.

Cheers!

Now with the Facebook Like Button!

Obviously, the Facebook Like button is one you’d like to implement inside your blog, website or whatsoever. I did too, although I am quite late as everyone has theirs for ages, but why not share some thoughts about it and the whole social widgets riot? As we all know (or maybe suspect) the web is going social, and what value is your blog if your readers can’t share your article with their friends with a single click of a button?

Facebook’s gone wild for the last few months. They keep rolling out new features, extending their functionality, and allowing developers and website owners implement those features into their own websites. Of course Facebook’s not the only one with their funky F8 conference, the Javascript SDK and the Social Graph API, as Twitter introduced their @Anywhere platform at the SXSW conference. And what about Digg? Google Buzz? I can go on forever, but all these new features have some things in common:

  • The code is bullet-proof (with a few exceptions)
  • You don’t need third-party services such as Tweet Meme, etc
  • Everything’s well documented in several languages
  • They’re all incredibly easy to use and maintain

Right. Who needs those extra WordPress plugins when you can simply copy and paste a few lines of code into your sources? As long as you have a little bit of general HTML knowledge you’ll be fine. If you’re a developer though, you’ll find all these extras much more interesting than an average person. I’ll keep this post closer to what Facebook has to offer, but the thoughts are fair for others too.

If you’re into the Facebook Platform, then you must have had some experience with FBML, iframe coding for Facebook and Facebook Connect. After Facebook rolled out their official PHP library, things began to make more sense, as you don’t have to spend too much time reading the specs to their API, everything’s done for you and wrapped into a set of classes, well documented and ready for use. Amazing!

Now, let’s drop the PHP stuff and talk about javascript for a while. Facebook’s got a Javascript SDK, and the best part of it is that you don’t have to read at all! There it is, right on the homepage, a short snippet of javascript code, ready to be copy-pasted onto your website, and voila! You’re now officially pimped! And ..? And yes, returning back to our Facebook Like button, it’ll take you less than 3 seconds to install it as well as all the other sexy widgets.

The Facebook Like Plugin page is full of text for those of you who like to read, but just by looking at the form, it’ll take you 2 seconds to configure it, and one to grab the code in FBML. If there’s somebody who didn’t quite get it, here’s a snippet with the complete Like button:

<div id="body">
<!-- My FBML goes here -->
</div>
<!-- Facebook Javascript SDK -->
<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({appId: 'your_app_id', status: true, cookie: true, xfbml: true});
        FB.XFBML.parse(document.getElementById('body'));
    };
    (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    }());
</script>

What on earth could be easier than that? Hello World? ;)

Now that you’re boosted with the Facebook Javascript SDK, you can go on and grab some other sweet plugins such as the Activity Feed, Comments, Friendpile and the rest. Experiment with the UI, sizing and positioning and you should be able to fit the widgets anywhere on your website. P.S. The Facebook Like button’s minimum width is 90 pixels.

You won’t (or at least shouldn’t) have any trouble installing other social widgets onto your website, including Twitter, Digg and Buzz. There are tonnes of articles out there that explain the whole process step by step, but if you’re experienced enough, you’ll be fine just by scanning through the code.. Hope you didn’t scan my article that way ;)

Anyways, the bottom line is that Facebook (and everyone else) are doing quite good at providing tools to fulfill your website with the social juice available. Oh, and don’t forget to “Like” this post, and of course retweet. Cheers!