Twitter follower count in WordPress with new Twitter API 1.1

T

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.

About the author

Zvonko Biškup

A passionate web developer with more than 13 years experience in PHP and other web related technology. My main interest is WordPress and new PHP frameworks.
Owner of Influendo Programming.
Enjoys exploring new stuff and possibilities, using new technologies and just having fun developing awesome stuff.

<span class="dsq-postid" data-dsqidentifier="1823 https://www.codeforest.net/?p=1823">18 comments</span>

Tags