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!

How to Count Facebook Fans in PHP

Update: There’s an new easier way of retrieving the fans count using the Graph API, covered here: Counting Facebook Fans in PHP: The Graph API Way

Not too tricky this one, but very handy as the social media world is developing extremely fast. It may not be too useful to publish the fan count of your facebook fan page if you’ve got less than a hundred or so, but as soon as you jump that high, it’s a good idea to show people that they’re not the only ones following you. Same applies to Twitter and other social media platforms.

The code is fairly simple if you’re familiar with the Facebook API, and even easier if you ever used the Facebook Client for PHP library, which makes tackles this issue in (literally) three lines of code and a simple FQL query. Don’t forget that in order to work with the Facebook platform, you’ll need an API key and secret. If you haven’t got a developer account, follow this guide to set it up.

That’s probably the most difficult part of this article. Once you have a dev account and the PHP client library, all you do is:

require_once('facebook/facebook.php');
$facebook = new Facebook('api_key','api_secret');
$fql = 'select fan_count from page where page_id = your_page_id;';
$result = $facebook->api_client->fql_query($fql);
$fb_fans = $result[0]["fan_count"];

Please note! that the code above is fine for the old version of the Facebook PHP Client. They released a new one which handles things a little bit differently, so here’s the code for the new version (tested in 2.0.4):

require_once('src/facebook.php');

$facebook = new Facebook(array(
  'appId'  => 'your_app_id',
  'secret' => 'your_app_secret',
  'cookie' => true,
));

$result = $facebook->api(array(
	'method' => 'fql.query',
	'query' => 'select fan_count from page where page_id = your_page_id;'
));

$fb_fans = $result[0]['fan_count'];

Replace api_key and api_secret with your own keys and secrets, replace your_page_id with the numerical ID of the page you’d like to quote. Also, if you’re unsure what is returned, then you should run a few checks on $result using print_r or var_dump.

Well.. That’s it! I just came across this issue last week and thought somebody might find it useful. Also note that in order to optimize the load time of your page, you should cache the result for some time, perhaps a day or two. Same applies to Twitter followers count and anything else you’re doing via public APIs (unless you’re using a javascript widget of course).

Facebook-style Lightbox with jQuery and Facebox

I recently came across an awesome plugin for jQuery which is called Facebox. Facebox produces a clean lightbox that can be a container for popup images, text and basically any HTML layout as well as AJAX powered content.

The problem with Facebox is the lightbox placement. The dialog itself is placed in the center of the page horizontally with a preset margin from the top, which looks good, but what I did notice is that the box containing the loading icon is being placed somewhere to the left part of the page. Well at least on Firefox 3.5.7.

I couldn’t help but noticing that FamSpam and StaffTool are using a different set of functions and styles for the lightbox placement and copying them into my code solved the issue.

The two functions are called getPageScroll() and getPageHeight() and are marked as quirksmode.com inside the code. The #facebox style in the CSS lacked a width: 100% which seems to have solved the issue for now. There’s also a certain overlay in the original version which includes an interesting IE6 hack:

height: expression(document.body.scrollHeight > document.body.offsetHeight ?
	document.body.scrollHeight : document.body.offsetHeight + 'px');

The versions at Stafftool and FamSpam however don’t mention any overlays in there code. Pretty messy, huh? Well, other than that, the plugin is very lightweight and cross-browser, works well in IE and closes the popup when pressing Esc, which unfortunately has to be hand-coded in other versions of the Facebook-style dialog boxes.

Grab the code at GitHub and enjoy: Facebox for jQuery.

The Facebook Platform: Building a Custom Fan Page

As you may have heard, I’m only starting as a Facebook developer and with a few recent experiments, Timothy and I thought about customizing a fan page on Facebook, which will hopefully soon take advantage of its own domain name (Facebook’s Open Graph API). This is less of a technical post and more of a thinking one. We started our new experiment on a Sochi 2014 Olympiad fan page on Facebook and we’re trying to replicate one of the the original websites (sochi2014.com) inside the fan page canvas.

Errm.. I’d like to give a huge shoutout to the talented (sarcasm) developers of sochi2014.com! Well, on the outside the website looks okay, but on the inside, oh brother, give me a break! I’ll point out the most interesting and fun ones:

  • Starting from the first line: no document type definition
  • I noticed an empty table with a cellpadding=3, is that the new standard for margins? ;)
  • Check out the script type=”” language=”javascript”, what the hell does that mean?
  • Wow, &nbsp; heh, haven’t seen that for a while!
  • Cool, they’re replacing margin-top: 1px; with an empty.gif height=1 image!
  • Closer to the bottom of the page, I found 11 closing divs right next to eachother.. I don’t believe that they’re using a minify script for that one
  • And ~ 50 errors according to the W3C HTML validator, I don’t think there’s a reason to mention them all

That’s probably enough for a start. Very frustrating when a website like that is being built like *that*, and with a page rank of 8! I’d give those guys a solid 2 ;)

Now, back to Facebook. I registered a new application, did some setup and managed to get a four-page website, similar to sochi2014.com, inside apps.facebook.com, with a few modifications (and cleaning up of the code), including a dashboard and a tabs widget for navigation. This was quite straightforward and simple to do (take a look at the Facebook API Developers Guide), the linking structure was okay, the contact form was done in only a few seconds (thank you Facebook for your great FBML!) and the static pages were simply some copy-pasting.

Once I got that up and running I decided to port it into the fan page (as an application tab) that Tim and I manage. I was quite surprised that all the linking structure died, but was pleased that I could at least see the front page, besides the fact that you have to click on the flash element before it’s shown. With a few more experiments and some help from the Facebook Platform Developer Forum (which is a very sweet place btw) I came to a conclusion that multipaging will not work in application tabs on profiles and fan pages. The easiest way around this is of course to use FBJS (javascript) to imitate multiple pages by hiding and showing certain elements on mouse click events. Forms would be a problem too, unless submitted via Mock AJAX.

Tim then asked me if I could move the menu I built up to the top where the main tabs are (Info, Wall, Photos, etc) which seemed impossible. Well, at least from within one Facebook application. So if I’d like to have 5 tabs at the top of the fan page I’d have to register 5 new Facebook applications, what a mess! Wouldn’t it be easier to manage a certain amount of tabs within one application and let profile owners and fan page administrators decide which ones they’re going to put up their navigation? Oh well.

It’s very strange though why companies aren’t yet taking full advantage of what fan pages might look (and work) like. Let’s take a look at Mashable’s Killer Facebook Fan Pages. Out of the 5 pages featured there, the Redbull Fan Page is the one I liked most. They have FBJS pagination, flash video and links to their application page which is quite interesting (yet still a single page with minumum user interaction). The Adidas Originals custom fan page is fully based on Flash, which is why they ask you to “Click to Enter” before you could see anything. The Starbucks and Coca-Cola pages are less interesting, simple HTML with links to external pages. The Pringles fan page doesn’t even have an app of it’s own – Killer?

Here are a few other pages worth checking out. Smashing Magazine – they’ve got two sections: “The Smashing Book” and “Write for Us”, which are two different Facebook applications (judged by the URL). The BMW Fan Page features an interactive form with FBJS validation and submission – way to go guys! And I’m pretty sure there are tonnes of others which I didn’t come across.