Adding your Twitter followers as a number on your website is a little more difficult than adding Facebook likes, but it’s doable, thanks to WPBeginner.
Here’s what we’ll be creating (Twitter only):
First, you’ll need to create a Twitter Application.
Once your application is created, click on the API Keys tab to find your API Key and API Secret.
Copy and paste the following code into your theme’s functions.php. The only code you need to replace are the values for $consumerKey and $consumerSecret with your new application’s “API Key” and “API Secret”, as well as your screen name.
// Get # of Followers as Number
function getTwitterFollowers($screenName = 'ADD_TWITTER_SCREEN_NAME_HERE')
{
$consumerKey = 'ADD_API_KEY_HERE';
$consumerSecret = 'ADD_API_SECRET_HERE';
$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;
}
Next, you’ll just need to paste this code into your theme’s code where you want the number to show:
And that’s it! Of course there are a few plugins that do this exact same thing (if you’re using WordPress). The best plugin I’ve found is called Social Count Plus and you can download that here for free.
If you’ve found this tutorial useful, please share it below: