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:
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";
set_transient($cacheKey,$output,3600);
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:


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

Related Articles

6 COMMENTS

  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 api.twitter.com:443

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Try EchoTools - my free, iOS ultrasonography reference application!

Latest Articles