Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

How to Display Twitter Followers Count as Text in WordPress

Last updated on by
Follow WPBeginner on YouTube
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.wpbeginner.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


Editorial Staff at WPBeginner is a team of WordPress lovers led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »
  • http://www.wpbeginner.com/ WPBeginner Staff

    Yes with a few changes you can use it with any PHP application.

  • arun

    It is not working for me.
    I have added that code into sidebar template , then i replaced consumer key and secret key with screen name. Still it is not working
    This is my page url

    • http://www.wpbeginner.com/ WPBeginner Support

      Arun it seems like you resolved the issue, when we visited your webpage it was showing the correct twitter follower count in plain text.

  • Nic Granleese

    Hi,

    Can you tell me if this code works for multiple twitter users.
    I’m trying to make a table with different users on a site with their respective twitter follow count.
    When I tried it seems to display only one twitter user’s count, which I assume is because user one get’s cached, and then the second, third, and n users just display the same result.

    Nic

    • http://www.wpbeginner.com/ WPBeginner Support

      Yes you got that right.

  • Julian Lara

    Its possible to get a comma in the number like 140,029. Because actually show like 140029.

  • rayuribe

    works great!
    but…
    It is possible add the result of this script to this other >

    http://lineshjose.com/blog/how-to-display-facebook-fans-count-as-text-in-wordpress-site/

    and show the total? (facebook_fans+twitter_fans=total_fans)

  • Nazar

    This doesn’t work for me.

    I’ve replaced $consumerKey and $consumerSecret as well as made the Access level to “Read and write” but nothing is happening :|

  • irfan

    Hey hi,
    Such a great post.
    I have ask a question for you I use twiiter user link (https://twitter.com/screen_name) when i use this link show followers its that possible?
    Any one,
    Thank Advance

  • Alvin

    Hello,

    we get this error

    Fatal error: Call to undefined function get_option() in line 17

    line 17 is this

    $token = get_option(‘cfTwitterToken’);

  • Matt

    Hi,

    Dreamweaver tells me this line is invalid:

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

    So I’ve updated it to:

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

    But the twitter count just says 0 (I have over 1,200).

    Any suggestions?
    Thanks!
    Matt

  • Malcom Miles

    Wrapped this tutorial along with the “WordPress Site Specific Plugin” tutorial and worked like a charm.

    Many thanks! :3

  • Tyler

    I’ve tried doing this atleast 10 times and can’t get it to work. Is it up-to-date?

    • http://www.wpbeginner.com Editorial Staff

      Yes this code was recently updated, and it works fine for us.

  • Zulhilmi Zainudin

    How about to display Facebook Fans & Google+ Followers in text?

  • Chandra

    Thanks for this code. I used this in my site but after sometime, I tested with an addition of follower but that count is not being updated. It still shows old count. Is something missing ? Thanks.

    • Chandra

      Ah, it updated after an hour or so…

  • regnar

    A little demo would be great.

    • http://www.wpbeginner.com Editorial Staff

      It will show the count as text. For example: if you have 100 followers, then it will output 100. Not sure what you expected in the demo.