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:
- You already have a Twitter application registered through the developer site.
- You’ve downloaded twitterOAuth and uploaded the folder to your WordPress theme folder (“../wp-content/themes/your-theme-name/”)
- You know how to handle your theme’s functions.php file. Paste the following code into said file:
<?php
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.
$twitterConnection = new TwitterOAuth('YOUR_CONSUMER_KEY','YOUR_CONSUMER_SECRET','YOUR_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN_SECRET');
// 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";
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:
<?php echo twitterCounts('twitterUsername'); ?>
Let me know if you ran into any trouble via the comments section! 🙂



Leave a Reply