UPDATE: This code no longer works as Twitter retired v1.0 of their API. v1.1 of their API requires authentication in order to access it. I have no plans to update this code for their new API. Sorry.
Konstantin Kovshenin posted some code on his blog for how to display how many Twitter followers someone has. While the idea was good, I think he went about the implementation in the non-best method. So, for fun and because I don’t post enough code snippets here on this blog, I thought I’d post how I would display how many followers someone has on Twitter. 🙂
function viper_twitter_followers( $username = 'Viper007Bond' ) { // Just to keep the code below cleaner, create the cache key now $cache_key = "viper_twitter_followers_{$username}"; // First we look for a cached result if ( false !== $followers = get_transient( $cache_key ) ) return $followers; // Okay, no cache, so let's fetch it $result = wp_remote_retrieve_body( wp_remote_get( 'http://api.twitter.com/1/users/show.json?screen_name=' . urlencode($username) ) ); // Check to make sure we got some data to work with if ( empty($result) ) { // Cache the failure for 1 min to avoid hammering Twitter set_transient( $cache_key, 0, 60 ); } // Parse the data $data = json_decode( $result ); // Make sure we were able to parse it // If not, cache the failure (like above) if ( !isset( $data->followers_count ) ) set_transient( $cache_key , 0, 60 ); // Success! Cache the result for an hour. $followers = (int) $data->followers_count; set_transient( $cache_key, $followers, 3600 ); return $followers; } echo 'I have ' . viper_twitter_followers( 'Viper007Bond' ) . ' followers on Twitter!';
Reading Material:
- HTTP API: http://codex.wordpress.org/HTTP_API
- Transient API: http://codex.wordpress.org/Transients_API (expiring options basically)
If you have any questions about the above code, let me know and I’ll do my best to answer them. 🙂
Allow comment only if viper_twitter_followers > threshold?
;-p
Pingback: Twitter followers count (and much more) in WordPress | Rarst.net
Unless you really want to store the follower count in WordPress I’d skip PHP entirely and use JavaScript along with the JSON API that Twitter provides. The statuses/user_timeline method provides followers_count. It wouldn’t be hard to add it to my JavaScript example for showing your last tweet.
A very valid point and that’s how my follower count is shown in my sidebar (although I didn’t write that code).
I more wrote this post for the purposes of proper PHP technique than to actually fetch your follower count.
What would be advantage of making user load jQuery (if not already), then extra script, then making Twitter API request client-side as opposed to serving him three bytes of cached count inline with PHP?..
@Joseph – Sorry for the kibitz, Alex, but I gotta say: gawwwd that’s sweet. Truly, it’s a real lift to see folk coding as if it’s actually 2010. cheers –ben
Great job Alex, nice work around different Twitter names, and thanks for the HTTP API hints 😉
~ K
Pingback: Twitter Followers Count Snippet for WordPress
nice. didn’t know about the transients. I’ll have to update my twitter widget to use that instead of get/update_option 🙂
For the sake of comparison: Get Total Twitter Followers With jQuery (21MAY2010)
Pingback: Mostrar los followers de Twitter con jQuery | ceslava - Diseño y Formación
Thanks for this. What’s the best way to put it in the sidebar? Is there a way (however funky it may turn out) to use a widget for this?
This was more a coding exercise than anything. If you want a proper plugin, then I recommend this one: http://wordpress.org/extend/plugins/wickett-twitter-widget/ It’s the one we use on WordPress.com. 🙂
Whoops, I’m an idiot. You were looking to show your number of followers (duh) and not your recent tweets. Silly me.
I don’t know of any such widgets off the top of my head. This code could be ported into a widget though, but it’s a big more complicated than I could explain in a comment.
If you happen to be a coder though, here’s where to start: http://codex.wordpress.org/Widgets_API
That’s OK! It’s a cool thing but not so critical that I’d want to go through the coding exercise for it. lol Maybe later.
What you’ve provided is very helpful, though! One day someone will create a plugin for it (one better than Twitter Counter) lol. Til then!
Cheers,
Tia
I got this error.
Fatal error: Call to undefined function get_transient() in D:\xampp\htdocs\twitter\example4.php on line 8
get_transient()
is a core WordPress function. If you’re going to use this code outside of a theme, you need to load WordPress by includingwp-load.php
.Great snippet viper. Ive been looking around for a viable option other than the one i currently have installed. Ive been using the following code:
The problem is (while in WordPress debug mode) it gives me the following error:
Warning: SimpleXMLElement::__construct()
This error is repeated over 20+ times with tonnes of gibberish.. (ill document the error the next time it happens if your curious)
Whats your take on this? How does the code snippet you posted differ from the one im currently using?
You’re fetching the data in XML format, I’m fetching it in JSON. You’re also using a WordPress pseudo cron to update the data while I’m using an expiring transient to do it. There’s nothing wrong we the code you use other than I’d recommend using the WordPress HTTP API instead of CURL. If you’re on PHP5 (which you should be), I’d also just use simplexml_load_string() instead of a SimpleXMLElement class instance.
what are the benefits of using the WordPress HTTP_API versus CURL? and how would i alter the code above to your recommendations? Im pretty sure ill be lookin at errors on my screen, if i alter it.
appreciate the advice viper. cheers.
The WordPress HTTP API is significantly more robust. For example not all webhosts have CURL installed. The WordPress HTTP API will automatically select the best method for contacting the remote server. It may very well select CURL, but it might also select a better alternative. It all depends on the server configuration.
It’s also a lot easier to use as it’s only one or two function calls.
Amazing snippet.
Hands down the best one for this purpose.
Thanks.
This is the exact thing I am searching for last few hours.. the next thing I need to figure out is a way to display FB Likes as text.
been using this for a while. Lately though it returns 0 followers though we have over 5000. I think twitter changed its api at some point. Might that be the problem?
BTW, thanks for all the coding you do. We use the video plugin on all our sites and love it.
t
Yes, Twitter retired v1.0 of their API which my code was using. v1.1 requires authentication to access their API so it becomes a lot more complicated.
You’re probably best off just using Twitter’s official follow button with the followers count enabled: https://dev.twitter.com/docs/follow-button
Thanks. I figured as much. A developer we used to create a theme hard coded this code snippet in. When I saw viper_twitter_followers I thought it was you (only a few vipers out there as well known! lol)
We’ll look into the button plugin.
Thanks again!
tim