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. :)

26 thoughts on “Twitter Followers Count Snippet for WordPress

  1. Pingback: Twitter followers count (and much more) in WordPress | Rarst.net

    • A very valid point and that’s how my follower count is shown in my sidebar (although I didn’t write that code).

      I more wrote this post for the purposes of proper PHP technique than to actually fetch your follower count.

    • What would be advantage of making user load jQuery (if not already), then extra script, then making Twitter API request client-side as opposed to serving him three bytes of cached count inline with PHP?..

  2. Pingback: Twitter Followers Count Snippet for WordPress

  3. nice. didn’t know about the transients. I’ll have to update my twitter widget to use that instead of get/update_option :)

  4. Pingback: Mostrar los followers de Twitter con jQuery | ceslava - Diseño y Formación

  5. Thanks for this. What’s the best way to put it in the sidebar? Is there a way (however funky it may turn out) to use a widget for this?

  6. That’s OK! It’s a cool thing but not so critical that I’d want to go through the coding exercise for it. lol Maybe later.

    What you’ve provided is very helpful, though! One day someone will create a plugin for it (one better than Twitter Counter) lol. Til then!

    Cheers,
    Tia

  7. Great snippet viper. Ive been looking around for a viable option other than the one i currently have installed. Ive been using the following code:

    function update_twitter_count() {
    	$name = 'USERNAME'; // Replace with your Twitter account name!
    	$url = 'http://api.twitter.com/1/users/show.xml?screen_name='. $name;
    	
    	$ch = curl_init();
    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($ch, CURLOPT_URL, $url);
    	$data = curl_exec($ch);
    	curl_close($ch);
    	
    	$xml = new SimpleXMLElement($data);
    	$count = $xml->followers_count;
    	
    	$count = (float) $count;
    	$count = number_format($count);
    	
    	add_option( 'twitter_followers' );
    	update_option( 'twitter_followers', $count);
    }
    	
    /** 2.1: Print out the number of Twitter Followers */
    function twitter_count() {
    		
    	$option = 'twitter_followers';
    	$value = '50' ;
    	
    	if ( is_user_logged_in() ) {
    		echo "Admin, you have " . get_option($option) . " Followers";
    	} elseif ( get_option($option) > $value ) {
    		echo get_option($option) . " Followers";
    	}	
    }
    /**
     * Use WP Cron to run get_twitter_count() once an hour
     * Keeps Twitter follower number up to date
     */
    if (!wp_next_scheduled( 'your_hourly_hook' )) {
    	wp_schedule_event(time(), 'hourly', 'your_hourly_hook' );
    }
    add_action( 'your_hourly_hook', 'update_twitter_count' );

    The problem is (while in WordPress debug mode) it gives me the following error:

    Warning: SimpleXMLElement::__construct()

    This error is repeated over 20+ times with tonnes of gibberish.. (ill document the error the next time it happens if your curious)

    Whats your take on this? How does the code snippet you posted differ from the one im currently using?

    • You’re fetching the data in XML format, I’m fetching it in JSON. You’re also using a WordPress pseudo cron to update the data while I’m using an expiring transient to do it. There’s nothing wrong we the code you use other than I’d recommend using the WordPress HTTP API instead of CURL. If you’re on PHP5 (which you should be), I’d also just use simplexml_load_string() instead of a SimpleXMLElement class instance.

  8. what are the benefits of using the WordPress HTTP_API versus CURL? and how would i alter the code above to your recommendations? Im pretty sure ill be lookin at errors on my screen, if i alter it.

    appreciate the advice viper. cheers.

    • The WordPress HTTP API is significantly more robust. For example not all webhosts have CURL installed. The WordPress HTTP API will automatically select the best method for contacting the remote server. It may very well select CURL, but it might also select a better alternative. It all depends on the server configuration.

      It’s also a lot easier to use as it’s only one or two function calls.

  9. This is the exact thing I am searching for last few hours.. the next thing I need to figure out is a way to display FB Likes as text.

  10. been using this for a while. Lately though it returns 0 followers though we have over 5000. I think twitter changed its api at some point. Might that be the problem?

    BTW, thanks for all the coding you do. We use the video plugin on all our sites and love it.

    t

  11. Thanks. I figured as much. A developer we used to create a theme hard coded this code snippet in. When I saw viper_twitter_followers I thought it was you (only a few vipers out there as well known! lol)

    We’ll look into the button plugin.

    Thanks again!

    tim

Leave a Reply