Get Twitter Follower And Tweet Counts With API 1.1 On WordPress

Since Twitter is requiring OAuth authorization for all API 1.1 requests, I had to modify the function which automatically refreshed my Twitter follower and tweet count every hour (caching it using WordPress’ Transients API). The workhorse for this function is Abraham Williams’ OAuth PHP library.

This walkthrough makes several assumptions:

  1. You already have a Twitter application registered through the developer site.
  2. You’ve downloaded twitterOAuth and uploaded the folder to your WordPress theme folder (“../wp-content/themes/your-theme-name/”)
  3. You know how to handle your theme’s functions.php file. Paste the following code into said file:
function twitterCounts($username){

// WordPress Transient API Caching
$cacheKey = $username . '-cache';
$cached = get_transient($cacheKey);
if (false !== $cached)
	{return $cached;}

// Call and instantiate twitterOAuth. Modify the path to where you uploaded twitteroauth
include ('/includes/twitteroauth/twitteroauth.php');

// Replace the four parameters below with the information from your Twitter developer application.

// Send the API request
$twitterData = $twitterConnection->get('users/show', array('screen_name' => $username));

// Extract the follower and tweet counts
$followerCount = $twitterData->followers_count;
$tweetCount = $twitterData->statuses_count;

$output = $followerCount . " followers, " . $tweetCount . " tweets";
return $output;
} ?>

In the snippet above, change the fields to match your Twitter application’s keys, tokens, and secrets. To refresh the cache more/less often, change the ‘3600’ (towards the end) to something else. This represents the number of seconds till the counts refresh.

Finally, call the function as follows:

<?php echo twitterCounts('twitterUsername'); ?>

Let me know if you ran into any trouble via the comments section! 🙂

Related Articles


  1. Hi, Thanks for this.

    It works fine on localhost but fails on the remote host. Twitteroath referencing is ok but still doesn’t work. Any tips.

    Many thanks

  2. Nice! Thanks for this! I’ve run across an odd issue though. It works great on my localhost installation but when I install the theme on a live server, it stops working. Does Twitter only allow the consumer key, access token, etc. to be used on a single website at any given time?

    • As far as I know, Twitter’s limits are based on the number of API calls per time interval and not on the number of clients making said calls. What kind of error is being thrown… if any? Are you sure you referenced the twitteroauth.php file appropriately on your live server?

  3. Nice work!
    Do you know how to fix errors like
    Unknown SSL protocol error in connection to


Please enter your comment!
Please enter your name here

Try EchoTools - my free, iOS ultrasonography reference application!

Latest Articles