WPBeginner

Beginner's Guide for WordPress

  • Blog
    • Beginners Guide
    • News
    • Opinion
    • Showcase
    • Themes
    • Tutorials
    • WordPress Plugins
  • Start Here
    • How to Start a Blog
    • Create a Website
    • Start an Online Store
    • Best Website Builder
    • Email Marketing
    • WordPress Hosting
    • Business Name Ideas
  • Deals
    • Bluehost Coupon
    • SiteGround Coupon
    • WP Engine Coupon
    • HostGator Coupon
    • Domain.com Coupon
    • Constant Contact
    • View All Deals »
  • Glossary
  • Videos
  • Products
X
☰
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

WPBeginner» Blog» Tutorials» How to Display Twitter Followers Count as Text in WordPress

How to Display Twitter Followers Count as Text in WordPress

Last updated on August 14th, 2013 by Editorial Staff
69 Shares
Share
Tweet
Share
Pin
Free WordPress Video Tutorials on YouTube by WPBeginner
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: https://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

69 Shares
Share
Tweet
Share
Pin
Popular on WPBeginner Right Now!
  • How to Fix the Error Establishing a Database Connection in WordPress

    How to Fix the Error Establishing a Database Connection in WordPress

  • Checklist

    Checklist: 15 Things You MUST DO Before Changing WordPress Themes

  • Google Analytics in WordPress

    How to Install Google Analytics in WordPress for Beginners

  • Revealed: Why Building an Email List is so Important Today (6 Reasons)

    Revealed: Why Building an Email List is so Important Today (6 Reasons)

About the Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi. Trusted by over 1.3 million readers worldwide.

The Ultimate WordPress Toolkit

27 Comments

Leave a Reply
  1. venky says:
    Sep 6, 2016 at 8:37 am

    Hi used the same code in my site..but its not showing the follower counter of the twitter pages

    pls help me out ..

    Reply
  2. Noraly says:
    Feb 28, 2016 at 1:55 am

    update: after having one last look I saw I hadn’t activated the access token. So now it does show up, only way at the bottom of my sidebar. How do I move it up to a more logical place? Preferably within the text widget at the top, so I can include it with all my other social media links. Thank you!

    Reply
  3. Noraly says:
    Feb 28, 2016 at 1:34 am

    Hi all, hope you are still monitoring comments, since it’s an older article. I have copied the code in functions.php, replaced the key and secret (left the ‘ ‘ intact, was I meant to do that?). Then I copied the other bit in sidebar.php. Replaced the yourscreenname with my twittername. This doesn’t make it show up in the sidebar though. Should I do something with a text widget in the sidebar, where I want it to show up? Just putting the last line of code in a sidebarwidget doesn’t seem to be the trick. Would appreciate your help. Thanks!

    Reply
  4. WPBeginner Staff says:
    May 14, 2014 at 4:04 pm

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

    Reply
  5. Jitendra says:
    May 14, 2014 at 3:58 pm

    Can i use it in other PHP application? I mean any other application which is not WP.

    Reply
  6. arun says:
    Apr 1, 2014 at 5:36 am

    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

    Reply
    • WPBeginner Support says:
      Apr 1, 2014 at 4:41 pm

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

      Reply
  7. Nic Granleese says:
    Feb 7, 2014 at 9:13 pm

    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

    Reply
    • WPBeginner Support says:
      Feb 12, 2014 at 5:29 pm

      Yes you got that right.

      Reply
      • Thomas says:
        Apr 21, 2014 at 11:59 am

        I’ve got the same problem.
        When I ask for the follower count of three different accounts and display it on a page, it displays the same number three times. The number it displays is the exact follower count of the first account.
        Do you know how to fix this? :/
        Thanks in advance.

        Thomas

        Reply
  8. Julian Lara says:
    Jan 9, 2014 at 3:30 pm

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

    Reply
  9. rayuribe says:
    Jan 5, 2014 at 1:27 am

    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)

    Reply
    • jahirul says:
      Oct 23, 2015 at 10:29 pm

      Would you please share the code of follower count of yours? the function and the activation code, please.

      Reply
  10. Nazar says:
    Dec 18, 2013 at 6:51 am

    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 :|

    Reply
  11. irfan says:
    Nov 23, 2013 at 5:15 am

    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

    Reply
  12. Alvin says:
    Oct 23, 2013 at 10:25 am

    Hello,

    we get this error

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

    line 17 is this

    $token = get_option(‘cfTwitterToken’);

    Reply
  13. Matt says:
    Sep 25, 2013 at 6:26 am

    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

    Reply
  14. Malcom Miles says:
    Sep 23, 2013 at 2:11 pm

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

    Many thanks! :3

    Reply
    • jahirul says:
      Oct 23, 2015 at 10:32 pm

      would you give me the code or the link of your plugin please.

      Reply
  15. Tyler says:
    Sep 1, 2013 at 4:14 pm

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

    Reply
    • Editorial Staff says:
      Sep 3, 2013 at 3:18 pm

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

      Reply
      • jahirul says:
        Oct 23, 2015 at 10:35 pm

        Does it work in localhost with net connection?

        Reply
  16. Zulhilmi Zainudin says:
    Aug 26, 2013 at 3:32 am

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

    Reply
  17. Chandra says:
    Aug 25, 2013 at 10:33 am

    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.

    Reply
    • Chandra says:
      Aug 25, 2013 at 10:58 am

      Ah, it updated after an hour or so…

      Reply
  18. regnar says:
    Aug 14, 2013 at 8:59 am

    A little demo would be great.

    Reply
    • Editorial Staff says:
      Aug 14, 2013 at 9:59 am

      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.

      Reply

Leave a Reply Cancel reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Over 1,320,000+ Readers

Get fresh content from WPBeginner

Featured WordPress Plugin
WP Mail SMTP logo
WP Mail SMTP
Fix WordPress email delivery issues. #1 SMTP plugin. Learn More »
How to Start a Blog How to Start a Blog
I need help with ...
Starting a
Blog
WordPress
Performance
WordPress
Security
WordPress
SEO
WordPress
Errors
Building an
Online Store
Useful WordPress Guides
    • 7 Best WordPress Backup Plugins Compared (Pros and Cons)
    • How to Fix the Error Establishing a Database Connection in WordPress
    • Why You Need a CDN for your WordPress Blog? [Infographic]
    • 30 Legit Ways to Make Money Online Blogging with WordPress
    • Self Hosted WordPress.org vs. Free WordPress.com [Infograph]
    • Free Recording: WordPress Workshop for Beginners
    • 24 Must Have WordPress Plugins for Business Websites
    • How to Properly Move Your Blog from WordPress.com to WordPress.org
    • 5 Best Contact Form Plugins for WordPress Compared
    • Which is the Best WordPress Popup Plugin? (Comparison)
    • Best WooCommerce Hosting in 2020 (Comparison)
    • How to Fix the Internal Server Error in WordPress
    • How to Install WordPress - Complete WordPress Installation Tutorial
    • Why You Should Start Building an Email List Right Away
    • How to Properly Move WordPress to a New Domain Without Losing SEO
    • How to Choose the Best WordPress Hosting for Your Website
    • How to Choose the Best Blogging Platform (Comparison)
    • WordPress Tutorials - 200+ Step by Step WordPress Tutorials
    • 5 Best WordPress Ecommerce Plugins Compared
    • 5 Best WordPress Membership Plugins (Compared)
    • 7 Best Email Marketing Services for Small Business (2020)
    • How to Choose the Best Domain Registrar (Compared)
    • The Truth About Shared WordPress Web Hosting
    • When Do You Really Need Managed WordPress Hosting?
    • 5 Best Drag and Drop WordPress Page Builders Compared
    • How to Switch from Blogger to WordPress without Losing Google Rankings
    • How to Properly Switch From Wix to WordPress (Step by Step)
    • How to Properly Move from Weebly to WordPress (Step by Step)
    • Do You Really Need a VPS? Best WordPress VPS Hosting Compared
    • How to Properly Move from Squarespace to WordPress
    • How to Register a Domain Name (+ tip to get it for FREE)
    • HostGator Review - An Honest Look at Speed & Uptime (2020)
    • SiteGround Reviews from 4196 Users & Our Experts (2020)
    • Bluehost Review from Real Users + Performance Stats (2020)
    • How Much Does It Really Cost to Build a WordPress Website?
    • How to Create an Email Newsletter the RIGHT WAY (Step by Step)
    • Free Business Name Generator (A.I Powered)
    • How to Create a Free Business Email Address in 5 Minutes (Step by Step)
    • How to Install Google Analytics in WordPress for Beginners
    • How to Move WordPress to a New Host or Server With No Downtime
    • Why is WordPress Free? What are the Costs? What is the Catch?
    • How to Make a Website in 2020 – Step by Step Guide
Deals & Coupons (view all)
MainWP
MainWP Coupon
Get 15% OFF on MainWP WordPress multisite manager plugin.
Sprout Invoices
Sprout Invoices Coupon
Get 50% OFF on Sprout Invoices WordPress invoicing plugin.
Featured In
About WPBeginner®

WPBeginner is a free WordPress resource site for Beginners. WPBeginner was founded in July 2009 by Syed Balkhi. The main goal of this site is to provide quality tips, tricks, hacks, and other WordPress resources that allows WordPress beginners to improve their site(s).
Join our team: We are Hiring!

Site Links
  • About Us
  • Contact Us
  • FTC Disclosure
  • Privacy Policy
  • Terms of Service
  • Free Blog Setup
  • Free Business Tools
Our Sites
  • OptinMonster
  • MonsterInsights
  • WPForms
  • SeedProd
  • Nameboy
  • RafflePress
  • Smash Balloon

Copyright © 2009 - 2021 WPBeginner LLC. All Rights Reserved. WPBeginner® is a registered trademark.

Managed by Awesome Motive | WordPress hosting by SiteGround | WordPress CDN by MaxCDN | WordPress Security by Sucuri.