Twitter Followers Count Snippet for WordPress

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

22 comments to Twitter Followers Count Snippet for WordPress

  1. Ben Tremblay says:

    Allow comment only if viper_twitter_followers > threshold?
    ;-p

  2. [...] many blogs and slowly become old, dirty, scary and unmaintained.So when Konstantin Kovshenin and Viper007Bond recently presented their modern take on Twitter followers count in WordPress I felt slightly guilty [...]

  3. Joseph Scott says:

    Unless you really want to store the follower count in WordPress I’d skip PHP entirely and use JavaScript along with the JSON API that Twitter provides. The statuses/user_timeline method provides followers_count. It wouldn’t be hard to add it to my JavaScript example for showing your last tweet.

    • Viper007Bond says:

      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.

    • Rarst says:

      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?..

  4. Ben Tremblay says:

    @Joseph – Sorry for the kibitz, Alex, but I gotta say: gawwwd that’s sweet. Truly, it’s a real lift to see folk coding as if it’s actually 2010. cheers –ben

  5. Great job Alex, nice work around different Twitter names, and thanks for the HTTP API hints ;)

    ~ K

  6. [...] 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 [...]

  7. Mile says:

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

  8. [...] Twitter Followers Count Snippet for WordPress (PHP) [...]

  9. Tia says:

    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?

  10. Tia says:

    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

  11. Ephron says:

    I got this error.

    Fatal error: Call to undefined function get_transient() in D:\xampp\htdocs\twitter\example4.php on line 8

  12. Aziz says:

    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.

  13. Aziz says:

    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.

  14. Oren says:

    Amazing snippet.
    Hands down the best one for this purpose.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

If you wish to post code, write it like [code]blah[/code] so it will display properly.