Twitter with WordPress

Update (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!