How to Use the Twitter API in WordPress
83Update (20 January 2013): There is a newer version of this script available now: Authenticate Your Twitter API Calls Before March.
There are plenty of Twitter plugins for WordPress. Why would we want to make our own script?
Well, most of the plugins come with a lot of fluff you just don’t need. Ours will be simple and efficient; all it needs to do is grab your tweets and display them.
The other reason is control; you write the markup, so it’s entirely up to you how it is displayed.
The last reason is that because we’re getting the tweets directly from the Twitter API feeds (i.e. no verification is going to be needed), we can easily display tweets from a Twitter List instead of just our own tweets.
(If you want to just grab the completed code, click here).
Start in the Sidebar
You can enter this wherever you like, the sidebar.php file is just an example. Just find where in your theme you want your list to be, and start by pasting the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <ul id="tweets"> <?php /* * JSON list of tweets using: * http://dev.twitter.com/doc/get/statuses/user_timeline * Cached using WP transient API. * http://www.problogdesign.com/wordpress/use-the-transients-api-to-list-the-latest-commenter/ */ // Configuration. $numTweets = 3; $name = 'problogdesign'; $transName = 'list-tweets'; // Name of value in database. $cacheTime = 5; // Time in minutes between updates. |
We’ll be listing several messages, so obviously a <ul> makes sense for displaying them. We’ve then put in a comment and some configuration options.
The links in the comment are to the relevant docs in the Twitter API, and to a tutorial here on Pro Blog Design about the transients API which we’ll be using in the next step.
The first 2 config options are self-explanatory, and the last two are to do with the transients (No need to change either of them).
What are Transients?
Transients are a great feature of WordPress. They allow us to store a value in the database for a limited period of time before deleting it. That gives us a very easy to use cache.
Twitter limits how often you can request information from it. By using the transients API, we can store the results for 5 minutes and then request them again.
For a full explanation, check out our post on using the transients API.
Check Our Cache
The first step is going to be very easy; we just want to look for our transient. If it exists, then we already have our tweets and can carry on, but if it doesn’t, then our first step is getting the tweets again.
1 2 | // Do we already have saved tweet data? If not, lets get it. if(false === ($tweets = get_transient($transName) ) ) : |
The line above checks for a transient, and saves it to the $tweets variable if it finds one. If it doesn’t, then we enter our if() statement.
Getting the Data from Twitter
There will be two steps in updating our saved tweets. The first is to get all the data from Twitter. The second is choosing the parts we need and formatting them.
Step one is very short:
1 2 3 4 5 | // Get the tweets from Twitter. $json = wp_remote_get("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$name&count=$numTweets"); // Get tweets into an array. $twitterData = json_decode($json['body'], true); |
The first line is the important one. The wp_remote_get() function is WordPress’ way of letting you grab a file (Thanks to Otto for showing me that in a comment on my last Twitter-related post! :) ).
The format of the link we give it is how we tell Twitter what we need. Full details are on the API page, but you’ll see it’s simple enough.
The cool part here is how easily we can change this whole script to embed tweets from a list instead. Literally the only change you would make to this whole post is to replace the URL here with this instead:
1 | "http://api.twitter.com/1/$name/lists/LIST_NAME_HERE/statuses.json?per_page=$numTweets" |
Just pop in your list’s name and carry on!
The second line, with json_decode(), took the file, and converted it into an array for us to use. It’s a PHP5 function by the way, so if you have errors at this part, doublecheck the version you’re using (Update 5th April 2011 – Another great comment from Otto here; WordPress defines this function for PHP 4.3 users, so it will still work there regardless!)
Save the Parts We Want
There are 5 pieces of information we want to get from each of the tweets:
- Username.
- Avatar.
- Tweet message.
- Tweet permalink.
- Tweet time.
If you’re only listing your own tweets, you could ignore the first two, but for completeness sake (i.e. anyone using Twitter lists), we’ll include them.
Let’s cover all of this in one go, and I’ll talk you through each section afterwards:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Now update the array to store just what we need. foreach ($twitterData as $tweet) : // Core info. $name = $tweet['user']['name']; $permalink = 'http://twitter.com/#!/'. $name .'/status/'. $tweet['id_str']; /* Alternative image sizes method: http://dev.twitter.com/doc/get/users/profile_image/:screen_name */ $image = $tweet['user']['profile_image_url']; // Message. Convert links to real links. $pattern = '/http:(\S)+/'; $replace = '<a href="${0}" target="_blank" rel="nofollow">${0}</a>'; $text = preg_replace($pattern, $replace, $tweet['text']); // Need to get time in Unix format. $time = $tweet['created_at']; $time = date_parse($time); $uTime = mktime($time['hour'], $time['minute'], $time['second'], $time['month'], $time['day'], $time['year']); // Now make the new array. $tweets[] = array( 'text' => $text, 'name' => $name, 'permalink' => $permalink, 'image' => $image, 'time' => $uTime ); endforeach; |
We start with a foreach() loop so that we can go through each of our tweets one at a time.
Lines 4 and 5 are the easy ones. The name is stored in our array, so we just have to pick that out. The permalink can then be made by combining the name and the tweet’s ID.
Line 8 gets the address of the avatar image. This is simple too in our case, because we’re happy to grab the default 48×48 image. If you want a different size though, check out this Twitter doc.
We get the message at line 10. The problem with the message as it is by default is that links are simple plain text, not clickable links. To fix that, we use a regular expression to reformat them into real links (Regular expressions are way outside the scope of this article, but you can read a great guide here).
At line 15, we get the time of the tweet. Later on, we are going to list our date in the “10 minutes ago” format, but to do that, we need the time stored as a Unix timestamp. Lines 17 and 18 do that for us.
Finally, in line 21, we add these 5 pieces of information to a new array.
And with that done, we save our new transient and end the original if() statement:
1 2 3 | // Save our new transient. set_transient($transName, $tweets, 60 * $cacheTime); endif; |
Display The Tweets
Now that we have everything we need, it’s just a matter of spitting out the info in whatever format you want.
Here’s how I’ve done it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Now display the tweets. foreach($tweets as $t) : ?> <li> <img src="<?php echo $t['image']; ?>" width="48" height="48" alt="" /> <div class="tweet-inner"> <p> <?php echo $t['name'] . ': '. $t['text']; ?> <span class="tweet-time"><?php echo human_time_diff($t['time'], current_time('timestamp')); ?> ago</span> </p> </div><!-- /tweet-inner --> </li> <?php endforeach; ?> </ul> <p><a href="http://twitter.com/#!/<?php echo $name; ?>">[ Follow us on Twitter ]</a></p> |
None of this should be too complicated. We take each tweet one at a time, put it in a list item and then print out the various details.
If you are only showing your own tweets, you’d probably want to take out the image (line 4) and the name (the start of line 7).
The interesting part is line 8. In it, we use an awesome WordPress function, human_time_diff(). All we have to do is give it two times (The tweet time and the current time), and it gives us that “10 minutes ago” effect. How easy is that?
To round it off, I’ve added in a link back to your Twitter profile.
And that’s us done. Now you have a simple and efficient way of listing your tweets, with no fluff and total control over the ouput. You can download the full code here.
I’d love to hear your thoughts on the tutorial! And if you have any other questions about working with Twitter in WordPress, let me know!
Enjoy this post? You should follow me on Twitter!
Excellent Michael! You’re really putting out a lot of great tuts recently :)
Thanks Pippin, really appreciate hearing that! I’ll try to keep it up :D
Yea this is really great. I am really liking the looks of the recent tweets in that image at the top of the post. What blog is that?
Nice tutor, but quite long.
I use the Api from tweetmeme, the coding just need about 6 lines. lol
Ah that’s cool. I haven’t really looked at Tweetmeme since the official Tweet button came out. With all the great tools Twitter itself makes (plus the API of course), it just seems to me that there isn’t much need to go through a third party anymore.
Very Important Tutorial MR Michael Martin Thanks you very much ;)
Hemmm nice.
You make it easy hehehe
Great Tutorial (From Indonesia)
That’s a quality tutorial, I just pasted it into the theme I was playing with and it worked without any problems. Quite often when i’m reading tutorials the source code isn’t quite right and needs tweaking :o)…… and I’d never even heard of the Transients API until now which is cool – I love learning new stuff!
Really glad you liked it Kevin! And thank you for leaving comments on quite a few of my posts recently, really rocks to see they’re being enjoyed! :D
Haha, I’ve had that exact problem before too. The worst part is that it’s always really silly things that break it, like renaming a variable as I’m writing the post. Now I’ve learnt to make all my changes to the live code first, never in the article! xD
Little heads up about something I discovered a while back (after I left you the last comment on the last twitter post :) ),
This code:
$json = wp_remote_get(...whatever...);
$twitterData = json_decode($json['body'], true)
Has a slight disadvantage in that $josn[‘body’] bit. The “body” is kind of a magic name, without any obvious reason for its existence unless you know HTTP a bit more than most people.
A somewhat better way is this:
$body = wp_remote_retrieve_body(wp_remote_get(...whatever...));
The wp_remote_retreive_body function in fact does the same thing, just returns the [‘body’] bit, but it makes things look somewhat cleaner.
There’s also wp_remote_retrieve_headers(), wp_remote_retrieve_header(), wp_remote_retrieve_response_code(), wp_remote_retrieve_response_message(), and various other utility functions like this, to assist in the use of the wp_remote_* functions. Check out the functions list in /wp-includes/http.php.
Ah, that’s pretty cool Otto! Anything that makes the code a little clearer is going to be better!
The only thing I still quite like about the array approach is that if you’re unsure about what it is, you can print out the whole array to see what’s in it (That said, I suppose one decent code comment makes your approach with the wp_remote_* functions better!)
Thanks for the heads up, I’ll definitely check them out! :)
Oh, also, json_decode is indeed a PHP 5 function, but WordPress includes a compatibility layer that defines it as well, so you can still use it within WP on a 4.3 system.
WordPress patches up support in PHP4? Really had no idea it went that far! That’s really impressive, very cool! :D (Updating the post now about that! :) )
Thanks for tip guys. very useful for me
Just got setup with Twitter and was having a hard time deciding on what to use with it. This helps a ton, thanks!
Great post, I was just thinking about writing my own WordPress plugin to track my latest plays from last.fm and I never knew about transients!
That’s a very cool idea Seth. Last.fm is great, sounds like a very handy plugin! :)
this was on my todo list this evening to go looking for and while procrastinating I landed on this – there u go – ur so good your tuts are actually reading my thoughts and getting me back to work with exactly what I need.
if only every day could be so sweet! Cheers
Ed
Glad you enjoyed it Ed! If there’s anything you ever want us to write about, just drop me an email! :)
Nice post, this will be very useful to implement in one of my blogs. I like it that you keep the code simple, other plugins are way to bloated I think.
Nice tutorial but since its lengthy i feel it will be little hard to implement. At present I use tweetmeme plugin. Anyway I am going to give a try on using the above codes.
I can understand what you mean about the length. Would you prefer to see a screencast instead of a written tutorial for a post of this length?
Great tutorial Michael – very useful. Personally I like the flexibility of tumblr do complete this kind of task at the moment, but may well implement some tweets on my blog at some point in the future. Have you written much about tumblr recently?
I haven’t written about Tumblr at all to be honest. I love the look of it, but haven’t gotten around to using it. I’d be curious to hear about any ways that you use it in conjunction with a self-hosted website (or blog). Would definitely make me want to explore it more then :)
No demo? :(
Sorry, I probably should start adding live demos to these tutorials. I always have screenshots, but that’s just not the same I guess :(
For this post, the demo would be somewhat as you’d imagine; a list of tweets in a sidebar. New design for PBD is coming soon, you’ll see this exact script in the footer then at least!
you are awesome michael, nice tutorial…
This is really an excellent stuff from you again.Thanks for sharing the tutorial and I am going to apply it in my wordpress blog.
nice tutorial…thnx mate….
The code was great at collecting the data from Twitter but I ran into problems because the account I was using it on has spaces in its ‘name’ that aren’t in the ‘screen_name’ and that meant links back to Twitter weren’t working.
Now it might be that I’ve done something really strange in the first place and had things behaving in a completely peculiar fashion…!? Either way my solution was to alter lines 4 and 5 in the core information:
$name = $tweet[‘user’][‘screen_name’];
$displayname = $tweet[‘user’][‘name’];
Add to line 23:
‘displayname’ => $displayname,
And changing the content of the tweet-inner div to make it display the account name as well as using the timestamp as the text for the permalink:
<a href="”> ago
Hopefully this time it will display the code. Ought to have escaped it…
/*
<a href="”> ago
*/
Shame I can’t tidy up after myself – no editing, deleting or previewing of comments :(
I’m clearly being incredibly stupid in not being able to post the code but what I did was replace
?php echo $t[‘name’] . ‘: ‘. $t[‘text’]; ?
with
?php echo $t[‘displayname’] . ‘: ‘. $t[‘text’]; ?
And then enclose
?php echo human_time_diff($t[‘time’], current_time(‘timestamp’)); ?
inside an containing the permalink
Awesome.. I will use it on my site…
It’ll be great things for me. If I could make it possible. WOW!!
Thanks for the tutorial, might use this as a guide in the next few months as we have a good few related projects in the pipeline.
Thanks brother….
I’m very helpfull…
Nice tutorial, Michael. Hmm..could you list some of best wordpress plugins that use Twitter service? It really could help people to decide which the best one is.
Great stuff Micheal, and worked first time – however what alterations would need to be made to list a search (like http://search.twitter.com/search.json?q=%23recipe+%23recipes)? I’ve given it a go but run into some problems – doesn’t need a name but needs *something* passed – maybe its just late at night and brain not functioning!
Thanks , help my site good..
Just FYI, you can easily add a twitter button to your blog quip card.
Great post Michael. But I’m wondering if it is possible to set something up that only pulls in “Favorited” tweets? The idea is to make it a Twitter Testimonial widget so that you can display all the great tweets people have put out in your name.
Great article, will try this out on our blog. Would this also work outside of the WordPress environment?
This tutorial has been a godsend, thanks so much! Quick question though — how would you go about truncating the tweet to a specific number of characters, in the event that you want to display the tweet in a location on a web page that requires the truncation to keep the layout tidy?
Any help is greatly appreciated. Thanks!
how would you go about truncating the tweet to a specific number of characters, in the event that you want to display the tweet in a location on a web page that requires the truncation to keep the layout tidy?
I just asked that question…? lol
If you want to convert Twitter usernames and hashtags into links as well as regular links, I used the following code and it seems to work nicely…
Replace this:
// Message. Convert links to real links.
$pattern = '/http:(\S)+/';
$replace = '${0}';
$text = preg_replace($pattern, $replace, $tweet['text']);
With this:
// Convert usernames, hashtags, and links to real links.
$patterns = array(
'#(http\://[^\s]*)#i',
'/@([a-z1-9_]+)/i',
'/(#[a-z1-9_]+)/i');
$replace = array(
'$1',
'@$1',
'$1');
$text = preg_replace($patterns, $replace, $tweet['text']);
Crap, the formatting didn’t work. Let’s try again…
Replace this:
// Message. Convert links to real links.
$pattern = '/http:(S)+/';
$replace = '<a href="${0}" target="_blank" rel="nofollow">${0}</a>';
$text = preg_replace($pattern, $replace, $tweet['text']);
With this:
// Convert usernames, hashtags, and links to real links.
$patterns = array(
'#(http://[^s]*)#i',
'/@([a-z1-9_]+)/i',
'/(#[a-z1-9_]+)/i');
$replace = array(
'<a href="$1" target="_blank">$1</a>',
'@<a href="http://twitter.com/$1" target=_blank">$1</a>',
'<a href="http://twitter.com/search?q=$1" target=_blank">$1</a>');
$text = preg_replace($patterns, $replace, $tweet['text']);
I was thinking to add a Twitter widget in my blog but not sure which one to use this has save me from adding another plugin on my blog.
Thanks Martin very nice Tutorials
-Imran
I’m very lucky to get this information from you.thank you
This is really an excellent stuff from you again.Thanks for sharing the tutorial and I am going to apply it in my wordpress blog.
Sweet, Twitter on my wordpress :)
You have made the work simple. i tried in a test theme and it worked great. I was not aware of API previously. Problogdesign makes me learn a lot of new things. I have a doubt. How you find these kind of topics. Many bloggers simply rewrite stuff from other sites but you’re always different. keep up the good work Michael.
Nice this article, your can fine wordpress jquery carousel
http://www.addcolours.com/blog/coding/how-to-create-a-jquery-carousel-with-wordpress
Hey Michael,
I’ve been using a modified version of this code on my blog for the last few weeks combined with a little sprinkle of jquery and it works really well (see latest from twitter under the main nav).
One major problem I have with it. When/If twitter goes down it throws a PHP error and breaks my site. While the ‘ol fail whale doesn’t happen as much these days – the odd time that it does happen it could cause problems for other people too. My PHP chops are not what they should be but it might be a good idea for someone to add some sort of try/catch around the twitter API call so that users sites dont break when twitter is down.
Ed
I have done a similar work.You have provided real learning through your blog.
This is one of the great blogs I’ve read today. Your site contains lots of good information and I’m sure many people will like it as I do. I would like to give this site a thumb up rating. Keep up the good works guys. I think I’m going to come back to this site regularly. Thanks.
Very ambitious and simplicity in the end of succeeding this marvel. I like it, no doubt. Matt you really should be shared with other great teams out there whom can enjoy your hard work.
This does take some time to do.
Once again congrates on this Matt keep on doin the good things that inspire creativity.
Great post, thank you ;)
nice work done..but please add some more stuff if possible..!!!
Hello there, Just wanted to say your website is rather excellent and I actually like the web site style and also the code.
At last I make it possible for me. And I found myself in a great condition. I’ve tried it on my blog and get advantages.
Great article. I never use twitter.
Great article, I don’t use twitter but maybe I will give a try.
I like to use twitter api rather than the plugins, which slower my blog big time.
Its very easy process. WordPress have some plugins which can be installed and activated in the site. So that twitter API will be integrated and twitter update will be shown in the site.
Is there a plugin available?
Just got setup with Twitter and was having a hard time deciding on what to use with it. This helps a ton, thanks!
Social media is such a big part of peoples websites now and are appearing all the time and not just for twitter. So this post is great when building wordpress sites as it makes it so easy to incorporate. Thanks for the post. It is so easy to follow with clear steps and screen shots to make sure I get it spot on.
I must say I’m so glad to find your blog, even though I did it by a fluke. The information posted here is so entertaining and different to the other blogs. In short, a really nice blog that I’ll keep visiting very often.
Just got setup with Twitter and was having a hard time deciding on what to use with it. This helps a ton, thanks!
You have made the work simple. Problogdesign makes me learn a lot of new things. I could found out excellent and useful information from you guys. I appreciate your work here. I like this type of post because it will be useful for everyone. Thanks.
just downloaded the code. its simple and easy to understand,great code! thanks
i wish i know how to write something with php and css
Great article, I don’t use twitter but maybe I will give a try. Thank you for the code.
I’d genuinely like to thank you for sharing this code. There are so many plugins out there that throw in the whole kitchen sink and don’t allow for customizing how it’s outputted and are intended to be used as widgets. This saved my butt today. Cheers!
Hi , I do believe this is an excellent blog. I stumbled upon it on Yahoo , i will come back once again. Money and freedom is the best way to change, may you be rich and help other people.
Hi, thanks so much! worked great, any tips on setting up Web Intents i.e. retweet link on individual tweets
Thanks for this – just what I needed! I have amended the regular expressions for replacing the links/hashtags/usernames:
$patterns = array(‘#(http\://[^\s]*)#i’,’/@([a-z1-9_]+)/i’,’/(#([a-zA-Z0-9]+))/i’);
$replace = array(‘$1‘,’@$1‘,’$1‘);
$text = preg_replace($patterns, $replace, $tweet[‘text’]);
sorry should have read:
$patterns = array(‘#(http\://[^\s]*)#i’,’/@([a-z1-9_]+)/i’,’/(#([a-zA-Z0-9]+))/i’);
$replace = array(‘<a href=”$1″ target=”_blank”>$1</a>’,’@<a href=”http://twitter.com/$1″ target=”_blank”>$1</a>’,'<a href=”http://twitter.com/search?q=%23$2″ target=”_blank”>$1</a>’);
$text = preg_replace($patterns, $replace, $tweet[‘text’]);
And before any eagle eyes point out:
$patterns = array(‘#(http\://[^\s]*)#i’,’/@([a-z1-9_]+)/i’,’/(#([a-zA-Z0-9]+))/i’);
no you don’t need the A-Z bit in the last pattern as the i modifier makes it irrespective of case (my mistake!)
$patterns = array(‘#(http\://[^\s]*)#i’,’/@([a-z1-9_]+)/i’,’/(#([a-z0-9]+))/i’);
Social media is such a huge part of websites now and are emerging all the time and not just for twitter. So this post is great when building wordpress sites as it makes it so easy to integrate. Thanks for the post. It is so easy to pursue with clear steps and screen shots to make sure I get it spot on.
I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks
I’ve tried this code for my two different Twitter accounts and it displays “No Tweets Found”, even when setting number of Tweets to 20, and yes, both timelines are public. Any idea what could be going on?