Twitter Followers Count Snippet for WordPress

Here’s a short snippet to grab and display your twitter followers count in WordPress. You can use this anywhere, sidebar, posts, header, footer. We’ll be firing an anonymous call to the Twitter API for a user profile. This method does not require authentication, unless you’re trying to view a protected profile. To make this slightly easier I’ve used the JSON functions which are available in PHP 5, but you can easily get them to work in PHP 4 (and as Alex mentioned in the comments below, WordPress comes with it’s own JSON functions for PHP 4 users, which is awesome).

I’ve modified the snippet a little bit due to comments below, and thank you again Alex (@Viper007Bond) for clarifying things with the WordPress HTTP API and those very useful Transients. I actually grabbed some ideas from Alex’s own version of the Twitter Followers Count for WordPress snippet and added a fail-safe route (for times when the Twitter API is down).

Anyways, the snippet now consists of a single function, which checks for a transient (for caching purposes), then fires a query to the Twitter API, and in case of an error return a stored followers count value from the past. In case the Twitter API responded fine, we set a new transient and store the value as the last successful. Here’s the new snippet:

// Use this function to retrieve the followers count
function my_followers_count($screen_name = 'kovshenin')
{
	$key = 'my_followers_count_' . $screen_name;

	// Let's see if we have a cached version
	$followers_count = get_transient($key);
	if ($followers_count !== false)
		return $followers_count;
	else
	{
		// If there's no cached version we ask Twitter
		$response = wp_remote_get("http://api.twitter.com/1/users/show.json?screen_name={$screen_name}");
		if (is_wp_error($response))
		{
			// In case Twitter is down we return the last successful count
			return get_option($key);
		}
		else
		{
			// If everything's okay, parse the body and json_decode it
			$json = json_decode(wp_remote_retrieve_body($response));
			$count = $json->followers_count;

			// Store the result in a transient, expires after 1 day
			// Also store it as the last successful using update_option
			set_transient($key, $count, 60*60*24);
			update_option($key, $count);
			return $count;
		}
	}
}

echo "I have " . my_followers_count('kovshenin') . " followers";

Yup, quite simple isn’t it? Now call my_followers_count whenever you need to retrieve your followers count ;) Hope this will be of use to someone ;) Cheers!