How to Get Your Twitter Follower Number in Plain Text
116It’s easy to use a service like TwitterCounter.com to get a little chicklet button of your Twitter follower number. If you have that number in plain text though, then you can style and integrate it into your site much more attractively. In this post, I’ll show you how to get it.
You can see the end result in the top right of Tiny Buddha, a site I recently coded using Chameleon (Though this will work on any WordPress theme!)
And you can download the completed code here.
Quick Overview
To do this, we will create 3 functions, to:
- Get the follower count from Twitter, and save it to your database.
- Retrieve that count whenever you need it.
- Update the count automatically every hour.
We add in the extra steps of saving to your database and updating because on a busy site, Twitter will cut you off for pestering their servers too much.
1 – Get The Follower Count from Twitter
There is an easy way to get an XML file from Twitter, which has all of the details about your profile. We’re going to use that file to find out your follower count.
You can see it at http://api.twitter.com/1/users/show.xml?screen_name=YOURNAMEHERE (e.g. Here’s mine)
Start out by opening up your theme’s functions.php file (Or create a file with that name if your theme doesn’t have one. Chameleon users would do this in chameleon>custom>functions.php).
The first thing we are going to do is create a function which gets the follower count from Twitter, and saves that value to your database. Copy and paste the following between the tags of your functions.php file.
function update_twitter_count() { $name = 'problogdesign'; $url = 'http://api.twitter.com/1/users/show.xml?screen_name='. $name; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); $xml = new SimpleXMLElement($data); $count = $xml->followers_count; $count = (float) $count; $count = number_format($count); add_option('twitter_followers'); update_option('twitter_followers', $count); } |
At the very top, replace the name problogdesign with your own Twitter account name.
Now, let’s take a look at what the code inside this function is doing.
- The first 2 lines (Starting with $name =…) simply save the address of the XML file on Twitter.
- The next 5 lines (Starting with $ch =…) use cURL to get that file and allow PHP to work with it. cURL is a large topic that could do with several posts of its own, but if you want to find out more about it, take a look here.
- The next 2 lines (Starting with $xml=…) allow us to get one specific value from the XML file, and save it to the $count variable.
- The 2 lines after that (Starting with $count =…) cast the string as an integer (number), and then format that number with commas (e.g. 7686 becomes 7,686). You can also set how number_format works (e.g. some European countries would list that as 7.686)
- The add_option line creates a new row in the wp_options table of your database, for storing a value called ‘twitter_followers’. When you next run this and the row already exists, this line won’t do anything.
- The final line, update_option, updates the value of ‘twitter_followers’ with the count we have just worked out.
2 – Retrieve the Value
This next function is just one line to print the value from the database option we just saved.
Copy and paste this below the previous function:
function twitter_count() { echo get_option('tb_twitter_followers'); } |
3 – Update Hourly
Last of all, we are going to use the WordPress Cron to automatically run our update function every hour. Copy and paste this final function below the other two:
if (!wp_next_scheduled('your_hourly_hook')) { wp_schedule_event(time(), 'hourly', 'your_hourly_hook'); } add_action('your_hourly_hook', 'update_twitter_count'); |
With the first 3 lines, we create a hook that is processed once every hour.
In the final line, we use add_action to attach our update function to this hourly hook. And you can attach as many other functions as you want to it.
If you’d like to learn more about scheduling events with WordPress, take a look at WP Engineer’s tutorial.
How to Display the Count
Now, anywhere in your template you can write and the number will be printed to the page for you, e.g.
<a href="http://twitter.com/problogdesign"><?php twitter_count(); ?> Followers</a> |
NB – This won’t work until the other functions have run once. You may want to manually call update_twitter_count() once to force it to happen right away (And then delete that call again!), or just wait an hour for the first scheduled run of it to happen automatically.
And that’s all there is to it! You can download a complete sample functions.php file to use in your theme here (just rename it to functions.php).
If you have any questions, feel free to ask them in the comments!
Enjoy this post? You should follow me on Twitter!
Here’s a much simpler way:
function get_follower_count()
// first check the transient
$count = get_transient('follower_count');
if ($count !== false) return $count;
// no count, so go get it
$count = 0;
$data = wp_remote_get('http://api.twitter.com/1/users/show.json?screen_name=Otto42');
if (!is_wp_error($data)) {
$value = json_decode($data['body'],true);
$count = $value['followers_count'];
}
// set the cached value
set_transient('follower_count', $count, 60*60); // 1 hour cache
return $count;
}
Replace the screen name with your own, obviously. Then just call this function whenever you want the count. It has built in caching for an hour, via the use of transients. No need for cron.
Thanks for sharing Otto. That definitely seems a shorter way to do it!
Thanks for the tips, it worked for me !
Otto, thanks for the configuration. This is excellent as I like going directly to the source for this. Question? TweetMeMe and some of the other plugins have shortcomings. One of those is that they don’t support redirects on domains or posts (which is needed from time to time). Is there a way to directly access RTs on a URL from Twitter like this? I’d like to have more control.
You’ve missed a { just after function get_follower_count()
okay. that’s very good job otto :D
that’s definitely a short way with the same result thank you for sharing this
I will use it.. thanks
nice article..!!
That’s a great little feature to add to a website. Maybe I’ll use someone elses screen name until I get more followers ;)
awesme! Thanks!
Hi Otto, first of all thanks for the code, it seems like it works for most of the people. I want to try it to, but my skills in PHP are 0.01. So, I put the code in functions.php, but how do I call it? If you could tell me this I would be very happy. Thank you.
nice thanks for sharing :D
Bad practice here: use curl functions, that may or may not be available, instead of wp_remote_ functions.
I hadn’t heard of the wp_remote functions until I saw Otto’s code above. Quick read over the Codex and they look great, definitely going to experiment with them instead in the future!
Please i am not using wordpress.. how do i implement this.. normal website
hi
please send me some example of this remote function, because on the above example i think there is some dependency so please guide me to do the same by using your way.
Regards
Hmm, now do I use Otto’s script or not? It does look easier. Otto, how can I call that into my theme?
Lou
Will have to play around with this some based on Otto’s and Ozh’s comments. Definitely has some potential with the ability to have more control over the design.
They’ve definitely made good suggestions here. Otto’s code includes Ozh’s recommendation (If you already have cURL installed on your server, then you’ll be fine with what’s in the post, but like Ozh said, it’s not guaranteed that you will have it)
Thanks.. this post really help to put twitter follower counter easily at wordpress. I just wanna know if we can put it (image/text) hover style.
Apartments for rent Bucharest
A simple way of showing number of followers on twitter is using Twitter counter buttons or you may use the WordPress plugin which has some badges to show counters.
I was just looking for this, you’re right in time
Nice share thanks
very excellent… tnx
Woa, it works! Thanks so much.
Great piece of information. Looking forward to checking this out. But one can always use wordpress plugins if on the WordPress platform, or the twitter counter.
Is there anyway to do this for facebook?
Sure thing Charlie. There are a few extra steps involved, but definitely possible. I’ll put up a tutorial for that in the next few days!
Look forward to hearing the good news from you. I’m a Facebook follower, so I really care about this. You know, I visit your blog almost everyday. It’s so cool and this is a place where I can find alot of helpful stuff. Thanks.
Hi, I found this snippet for Facebook. However, it works only for (fan)pages and not for your profile. I hope there will be a tutorial for that soon on this blog.
Thank you for snippet.
Very cool! Thanks very much for sharing this. Worked for me too.
ehk;d,,,,,,,,,
Very cool
thank you
nice code…. :D sure try it
Thanks for this tutorial!
Excellent info. Thanks for sharing :-)
Thanks for the tip. This will save me time calling it from my wordpress plugin!
Fantastic code – was looking for an example for Twitter followers and found this via a Google search. Forgive me in case I just didn’t search well enough, but you posted in the comments that you were posting a tutorial to do this with Facebook too… has that been posted yet? Thanks again for the great tutorial.
Great tip will try this one a tester blog before my main one. thanks
great idea .. thanks a lot.
Thank you for the info. Worked for me too :)
Works like a charm!
Great tip, i’ve used this for my own blog.
great website i like your blog and also this one post that is really nice post and informative
Sweet! You don’t really have to update it hourly though. One day at a time will save a lot of energy and doesn’t change much in the long shot :)
Thanks the post.
That seems a much simpler way to do it, thanks.
David.
Hey thanks for the tutorial. I’m going to start using this in place of the plugin im currently using which never seems to update!
Very nice Tutorial. Thanks a ton.
thanks a lot for sharing this wonderful tutorial
thank you Michael Martin. I immediately tried on the blog site.
Thanks a lot Michael .
Just what I needed
well thats looks good u10 article to read, but anyway i like it as much as u10 games
Intresting. Its not something that we need to do with every website as not everyone will have high numbers and want to show them off, but it can be well worth knowing for future websites.
Thanks for sharing this one
Nice job on that Tinybuddha site. The buttons and text look good. I’m curious to know about the code for the Facebook fans counter? Did you post that code anywhere yet?
Thanks for this, it really helped me out.
I don’t need this yet but I’m very glad I stumbled upon this. When my Twitter follow count is a little higher I might show this number…
Now I just have to remember were the article is.
gooooooooooood
thanks for this traning
Thanks for sharing this info. I had less than 100 followers and I was displaying it on my site. A fellow friend saw it and we chatted via Gmail chat and he told me to rather not display it as my followers were very low. Lets just say that I had just over 60 at that stage. It’s really helped me out…
http://commodityconsultant.com
Awesome!! Once again.. Michael on stucking somewhere i headed to problog… its like becoming my key blog to my learning.. thanks buddy :)
That’s awesome to hear! If there’s ever a topic you’d like to see here, just let me know! :)
i’ll try it soon guys :)
Very practical approach of the post. Thankful to the writer.
Wow, this is really usefull! I wonder what we could do soon with next twitter update after millions dollars investions! :P
Great post… thank you for sharing
Excellent tutorial, will have a try later on :), better plain text then that generated counter block
meanwhile I submitted the tutorial on the CMS tutorial site: http://cmstutorials.org/tutorial/view/how_to_get_your_twitter_follower_number_in_plain_text
where is the function.php file , and what directory should i put it… after setting function file up.. then what.. what is the database structure… the links.. how does this work..
Please i am not using wordpress.. how do i implement this
woww thanks
At the moment I don’t have a lot of followers so I don’t think it would be a good idea to show the number on my site. But I will bookmark this page because I think it will come in handy in the future.
Maybe you could use someone elses screen_name until you get more followers ;)
Thanks for sharing :) I did wonder how blogs displayed their followers. This is something I’ll add to my blog when I get a few more Twitter followers ;)
Very practical approach of the post. Thankful to the writer.
Does not work for me http://realwebdesigns.com/twitter/twitter.html
I have ever tried to display twitter follower number as a text, but sometime the number is missing, I need to refresh the page (once or even several times) to get the correct number.
I hope this tutorial would not have the missing number issue. Thanks for the nice share Michael :) I’d like to try it
I’m actually looking for this tutorial for quite some days, I saw someone who had this plain twitter counter on their site and I thought they were updating it daily. Instead of updating the twitter number hourly, is there any way to get it updating by every minute?
Thanks for the tutorial Michael.
Regards,
Lee
I don’t think updating the follower numbers every minute is a good idea, because API usage is rate limited with additional fair use limits to protect Twitter from abuse.
I tried this twitter follower code in one of my blogs and it worked fine without trouble. When directly copying and pasting some characters were created and it returned error. So i copied it to notepad and then pasted in functions file. it worked fine.
Ok so I did what the post by otto said, but it isn’t returning a count at this moment. Does it take an hour to get the initial count?
nice and great post i will use it on my site.
Thanks for your help
I got this twitter text right. I tried the same code with little changes for facebook but I couldn’t make it up. It would be helpful if you create a post for facebook.
wow, Thanks alot. I can show my twitter followers proudly on my blog now…hehehe I have 580+ :)
Very nice Tutorial. Thanks a ton, will try this tonight…
Hmmm, I just implemented this on my site, and the code seems to look fine. However it is not showing my count yet as the cron has not kicked in. I tried calling the function update_twitter_count() but there still is no counter! Am I missing anything special to call the functions?
If i use twitter & co i don’t know at the moment. I will remember your site that i kow it ;)
Thank’s, especially for “Update Hourly”
Will have to play around with this some based on Otto’s and Ozh’s comments. Definitely has some potential with the ability to have more control over the design
Perfect – thanks Michael & Otto. I’d been meaning to try to figure this out for a while. I guess if we’re going to show off our followers now, I’d better start working on building up those numbers!
thanks a lot, I will bookmark this article
that was useful. is there a way to show FB follower count and rss feeds too ?
thanks,
Sourish
Thanks! It is necessary to try to implement it on my blog!
Thanks for sharing . That definitely seems a shorter way to do it!
Sweet, thanks for the tip. This will help with my customer sites.
Thanks for the tip. I’ve been looking for something like this!
It was really great thing…i will sure use it in my blog…
perfect, thanks for sharing michael…
ya it is…
Ya, i am looking for this to my blog.
http://www.addcolours.com/blog
how to add lsit of all social meida follower numbers with plain text, like for twiiter, facebook, digg, stumble, RSS, Delicious.
Thanks, this is amazing !!!
thanks! but…how to do it for FACEBOOK?
yes, i also want to know how to do this in facebook…
wow! Amazing, i have created my new account there, need more no… then definitely i am gonna use this trikes! thanks for this wonderful sharing:)
wow that’s superb !!! i will try this defiantly ….!!!! i really need to enhance my followers !!!
was looking for this – thanks again mate!
I also try this tips.Its really work man..
Nice piece of code. Just what i was looking for! Thanks!
The closing paragraph tells all of it in my opinion. I must say that I agree with it, and the most wonderful thing about it is that you simply left it open ended…this reveals that you are prepared to draw in new and totally different opinions and that you’re finally very interested to see people getting concerned in the subject. So, any various opinions?
Thanks for this tutorial! Its a great help.
thanks for the article. I immediately tried it on the blog.
Very nice sharing of this great article. I really love reading your blog. Thanks for your nice job.
I think many plugins are in internet for doing this job.But doing manually is far better.
Delightfull information, thank you very much
Valuable information, thanks for sharing with us
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.
hey, and what about the Facebook?
Thanks for this posting!!
really useful! Just I must to test first lol :D