I had created the monster. Actually I adopted small cute code from Yoast then changed its flavor from FeedBurner to Twitter… And then I let it out on WpRecipes and it run away to wander over many blogs and slowly become old, dirty, scary and unmaintained.
So when Konstantin Kovshenin and Viper007Bond recently presented their modern take on Twitter followers count in WordPress I felt slightly guilty to nitpick on their code, when my is only worthy to be kept under wraps. So I lassoed my monster, took it home to NetBeans pens and spent some time on renovating it.
Common issues with Twitter snippets for WordPress
- poor integration – WordPress has extensive set of functions to ensure code works in many hosting environments, many snippets ignore that luxury and use generic functions;
- no caching – Twitter API has restrictive rules and snippets that bug it on every page load will easily exhaust limit, even on moderately visited site;
- no failover – snippets often assume best case scenario (guilty on many occasions myself) and you are left with errors and no value to show when something goes wrong;
- narrow scope – Twitter offers wealth of information, but most snippets are hardcoded for single user and returning followers count only, while you can get much more from it.
Code
function rarst_twitter_user( $username, $field, $display = false ) {
$interval = 3600;
$cache = get_option('rarst_twitter_user');
$url = 'http://api.twitter.com/1/users/show.json?screen_name='.urlencode($username);
if ( false == $cache )
$cache = array();
// if first time request add placeholder and force update
if ( !isset( $cache[$username][$field] ) ) {
$cache[$username][$field] = NULL;
$cache[$username]['lastcheck'] = 0;
}
// if outdated
if( $cache[$username]['lastcheck'] < (time()-$interval) ) {
// holds decoded JSON data in memory
static $memorycache;
if ( isset($memorycache[$username]) ) {
$data = $memorycache[$username];
}
else {
$result = wp_remote_retrieve_body(wp_remote_request($url));
$data = json_decode( $result );
if ( is_object($data) )
$memorycache[$username] = $data;
}
if ( is_object($data) ) {
// update all fields, known to be requested
foreach ($cache[$username] as $key => $value)
if( isset($data->$key) )
$cache[$username][$key] = $data->$key;
$cache[$username]['lastcheck'] = time();
}
else {
$cache[$username]['lastcheck'] = time()+60;
}
update_option( 'rarst_twitter_user', $cache );
}
if ( false != $display )
echo $cache[$username][$field];
return $cache[$username][$field];
}
Updates
- 2010-05-16 changed memory cache to single static variable (what it should have been in the first place) and to hold decoded JSON data instead of raw response.
Example usage
echo rarst_twitter_user('rarst', 'name').' has '.
rarst_twitter_user('rarst', 'followers_count').' followers after '.
rarst_twitter_user('rarst', 'statuses_count').' updates.';
Example result
Rarst has 247 followers after 3181 updates.
Features
As you see in example above this code is not limited to followers count. It can fetch any non-nested value returned by Twitter users/show API method.
It has two levels of cache:
- queried values are stored as array in database, using WP options, for $interval seconds;
- API responses are stored in memory so you can query any number of fields, without generating multiple API requests.
This should be safe to use for multiple values and multiple users at the same time, without worrying about exhausting API limit.
Shortcomings
I wrote this from start to finish in one evening so there may be things left to polish. Slightly worried about using variable variables for memory cache, but seems to work fine in my tests [changed to static variable].
I wanted to add error detection for cases when user name is mistyped and such. But WP HTTP API returns error and discards response data because Twitter API gives 404 on such requests. From googling around this behavior might be platform-specific (my local development stack is on Windows) and so tricky to get right.
Overall
Scary and bulky but powerful. :) And I am holding this one on a leash, feel free to point out issues and make suggestions to be implemented.
Alex (Viper007Bond) #
Rarst #
Konstantin Kovshenin #
Rarst #
How to Display Twitter Followers Count and More in WordPress #
Val Archer #
Val Archer #
Rarst #
echo 'Why are '.rarst_twitter_user('valarcher', 'followers_count').' readers following val archer on twitter today ?';
25+ Extremely Useful Tricks for the WordPress Functions File #
Val Archer #
Rarst #
WPExplorer #
Display Twitter Followers Count On Wordpress #
Rarst #
RSS And Social Media Hacks To Customize Your Wordpress Blog | Design your way #
Luke #
Rarst #
Social Statistics | George Wiscombe #
karthimx #
Rarst #
Tilo #
Rarst #
opa #