Twitter Followers Count Snippet for WordPress

UPDATE: This code no longer works as Twitter retired v1.0 of their API. v1.1 of their API requires authentication in order to access it. I have no plans to update this code for their new API. Sorry.

Konstantin Kovshenin posted some code on his blog for how to display how many Twitter followers someone has. While the idea was good, I think he went about the implementation in the non-best method. So, for fun and because I don’t post enough code snippets here on this blog, I thought I’d post how I would display how many followers someone has on Twitter. 🙂

function viper_twitter_followers( $username = 'Viper007Bond' ) {

	// Just to keep the code below cleaner, create the cache key now
	$cache_key = "viper_twitter_followers_{$username}";

	// First we look for a cached result
	if ( false !== $followers = get_transient( $cache_key ) )
		return $followers;

	// Okay, no cache, so let's fetch it
	$result = wp_remote_retrieve_body( wp_remote_get( 'http://api.twitter.com/1/users/show.json?screen_name=' . urlencode($username) ) );

	// Check to make sure we got some data to work with
	if ( empty($result) ) {
		// Cache the failure for 1 min to avoid hammering Twitter
		set_transient( $cache_key, 0, 60 );
	}

	// Parse the data
	$data = json_decode( $result );

	// Make sure we were able to parse it
	// If not, cache the failure (like above)
	if ( !isset( $data->followers_count ) )
		set_transient( $cache_key , 0, 60 );

	// Success! Cache the result for an hour.
	$followers = (int) $data->followers_count;
	set_transient( $cache_key, $followers, 3600 );

	return $followers;
}

echo 'I have ' . viper_twitter_followers( 'Viper007Bond' ) . ' followers on Twitter!';

Reading Material:

If you have any questions about the above code, let me know and I’ll do my best to answer them. 🙂