Tag Archives: Source Zvonko Biskup

How to Display Twitter Followers Count as Text in WordPress

The easiest way to display Twitter followers is by using the official Twitter follow button. But what if you don’t want to slow your site down by loading twitter’s script? Or what if you are making something very custom and need to display twitter follower count as text instead of a button. Well then you will like this tutorial. In this article, we will show you how to display your twitter follower count as text on your WordPress site.

Wondering how we are going to do this? Well, first we will create a Twitter App, so we can properly use the Twitter API v1.1 to pull the followers count. We will cache it to optimize performance, and then we will display it on the site. Ready to get started? Let’s go.

First thing you need to do is to create a Twitter App for the site where you want to display the followers count. Go to Twitter Developers website and sign in with your Twitter account. After signing in create a new application.

Creating a new Twitter app

On the next screen provide a name for your app this could be anything, ideally the title of your website. Provide a description for your app, this could be the same description as your blog or anything you want. In the website field enter the URL of your WordPress site, For example: http://www.google.com.

Enter the same URL in the Callback URL field as well. After filling the form hit the Create your Twitter application button at the bottom of the page.

This will create a new Twitter app for you to use. On the next page, click on Create my access token button. This will show you a notification that your authorization token has been created.

On your Twitter App’s page, we will only need the Consumer Key and Consumer Secret for the next step.

Copy the following code and paste it in your theme’s functions.php file or a site specific plugin. Replace Consumer Key and Consumer Secret variables with your consumer key and secret.

function getTwitterFollowers($screenName = 'wpbeginner')
{
    // 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;
}

Now add this line of code in your theme template where you want to display your twitter followers count. This could be in the sidebar.php, header.php, or basically anywhere you like.

<?php 
echo getTwitterFollowers('your_screen_name');
 ?>

That’s it. You are done. We hope that this article helped you show Twitter followers as text in WordPress. There are many other things that you can do to integrate twitter with your WordPress site. For example, you can add twitter cards, or display recent tweets in WordPress. To get more such useful tips consider following @wpbeginner on Twitter.

Source: Zvonko Biskup