on Tips

Twitter follower count in WordPress with new Twitter API 1.1

18 comments
Twitter follower count
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

Twitter API 1.1 is introduced on 11th of June and from that date the old 1.0 search API is discontinued.

There is a lot of tutorials around that uses the old API to get Twitter follower count, but unfortunately, those do not work any more.

One of the main changes to the API with the introduction of the 1.1 API is the implementation of rate limits and most importantly the upgrade to OAuth 2.0 for authentication. There is no more methods that can be called without authentication.

Create a Twitter Application

First step is to create a Twitter application and get your consumer’s keys. These are needed to use the oAuth 2.0.

  1. Point your browser https://dev.twitter.com/apps and login with your twitter credentials
  2. Create new application
  3. Fill in the form fields and create your app
  4. On the application page, click the “Create my access token”.

You will now have all kind of keys, but for this you will need only Consumer key and Consumer secret

Getting Twitter follower count

So, now we’re ready to start. I will show you how to get Twitter follower count in WordPress, but this code can be easily converted to any other.

Code below is heavily commented. So, basically you copy this to your theme’s functions.php file:

function getTwitterFollowers($screenName = 'codeforest')
{
    // some variables
    $consumerKey = 'YOUR_CONSUMER_KEY';
    $consumerSecret = 'YOUR_CONSUMER_SECRET';
    $token = get_option('cfTwitterToken');

    // get follower count from cache
    $numberOfFollowers = get_transient('cfTwitterFollowers');

    // cache version does not exist or expired
    if (false === $numberOfFollowers) {
    	// getting new auth bearer only if we don't have one
	    if(!$token) {
	    	// preparing credentials
	        $credentials = $consumerKey . ':' . $consumerSecret;
	        $toSend = base64_encode($credentials);

	        // http post arguments
	        $args = array(
	            'method' => 'POST',
	            'httpversion' => '1.1',
	            'blocking' => true,
	            'headers' => array(
	                'Authorization' => 'Basic ' . $toSend,
	                'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8'
	            ),
	            'body' => array( 'grant_type' => 'client_credentials' )
	        );

	        add_filter('https_ssl_verify', '__return_false');
	        $response = wp_remote_post('https://api.twitter.com/oauth2/token', $args);

	        $keys = json_decode(wp_remote_retrieve_body($response));

	        if($keys) {
	        	// saving token to wp_options table
	            update_option('cfTwitterToken', $keys->access_token);
	            $token = $keys->access_token;
	        }
	    }
	    // we have bearer token wether we obtained it from API or from options
	    $args = array(
		    'httpversion' => '1.1',
		    'blocking' => true,
		    'headers' => array(
		        'Authorization' => "Bearer $token"
		    )
		);

		add_filter('https_ssl_verify', '__return_false');
		$api_url = "https://api.twitter.com/1.1/users/show.json?screen_name=$screenName";
		$response = wp_remote_get($api_url, $args);

		if (!is_wp_error($response)) {
			$followers = json_decode(wp_remote_retrieve_body($response));
			$numberOfFollowers = $followers->followers_count;
		} else {
			// get old value and break
			$numberOfFollowers = get_option('cfNumberOfFollowers');
			// uncomment below to debug
			//die($response->get_error_message());
		}

		// cache for an hour
		set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);
		update_option('cfNumberOfFollowers', $numberOfFollowers);
	}

	return $numberOfFollowers;
}

That’s it. Just put below code to wherever you want to show your Twitter follower count:

echo getTwitterFollowers('your_screen_name');

I hope this will be useful for someone.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Yorgos Kousagiannidis

    Just wanted to say thank you…

  • http://szaboka.hu Roland Szabó

    Hey, man, thanks for this awesome tutorial.
    I’ve been really looking forward to find a short, concise method to get the number of my followers on Twitter. No bullshitting, no additional files to download, no hassling.
    Great one, once again! Thank you!

  • Toni

    Thnk by this code, but, if i don´t need to wordpress?? that i´ve that modify? Because failed me in “get_trasient” and “get_option”.

  • http://www.vermarktercheck.de Andy

    This code is way too complicated, you can use a different URL called https://api.twitter.com/1.1/users/show.json?screen_name=$screenName without this completely unnessesary loop in your code.

    • http://codeforest.net Zvonko Biškup

      Thanks Andy, you are right, I changed the code to use GET users/show command.

  • mike

    Hi Zvonko,

    thank you so much for this tutorial!

    Can you tell me how i can use this without wordpress?

  • Abu M Isaac

    Hi Zvonko,

    Thank you very much for this way of retrieving the follower count.

    Can you please help with building the same for non-wordpress site

    Thankyou

  • Lindsay

    This is great, thank you! Possible to format the output? For example, right now it returns “45678″ where I’d like it to return “45,678″. Any ideas on how to do this would be greatly appreciated!

    • http://codeforest.net Zvonko Biškup

      Hi,

      after retrieving numberOfFollowers from API, you need to format the number.
      So, after this line:

      $numberOfFollowers = $followers->followers_count;

      add this:

      $numberOfFollowers = number_format($numberOfFollowers, 0, '.', ',');

      If you used my code, this value is probably cached from before, so you need to wait until the cache expires to see the effect.

  • http://burfieldcreative.co.uk Neil Berry

    Great straightforward function. I had an issue with getting the count back on initial run of the code. Changed the lines:
    `
    // get follower count from cache
    $numberOfFollowers = get_transient(‘cfTwitterFollowers’);

    // cache version does not exist or expired
    if (false === $numberOfFollowers) {
    `
    to:
    `
    if (false === ($numberOfFollowers = get_transient(‘cfTwitterFollowers’)) ) {
    `

  • http://www.mattblank.com Matt Blank

    Hi,

    I get a PHP error with this line:

    $api_url = “https://api.twitter.com/1.1/users/show.json?screen_name=$screenName”;

    Can anyone help please?

  • http://mattblank.com Matt Blank

    It seems only to be showing 0, when I have over 1,000 followers.

  • http://www.atiqbd.com/ atik

    How could i reduce cache time?

    • http://codeforest.net Zvonko Biškup

      You can do that in this line:

      // cache for an hour
      set_transient('cfTwitterFollowers', $numberOfFollowers, 1*60*60);

      Last parameter is expiration in seconds, so if you put there 600, it will last for 10 minutes.

  • Dan

    Thank you… very helpful. Great blog!

  • Oneofanothers

    Hi, thanks for the tutorial, as the user Matt, I’m getting a 0 number as result. Anyone knows what’s happening?

    Thanks in advance