Latest Tweet in WordPress

Whilst looking for a plugin that would display my latest tweet on my homepage, I came across this post. I hadn’t realised it was such an easy task, hardly requiring an entire plugin.

I decided to adapt the code a bit, as fetch_rss() is now deprecated and I also wanted to display the date and time of the tweet, which this code doesn’t do as is.

I’m sure this isn’t really anything new, but I was just pleased with how simple it is to do. Here’s the code I came up with:

function latest_tweet(){
	$tweet_feed = fetch_feed('');
	$tweet = $tweet_feed->get_items(0, 1);
 	echo '<p>' . $tweet[0]->get_date('jS F, G:i') . '</p>';
	echo '<p>' . str_replace('rosshanney: ', '', $tweet[0]->get_content()) . '</p>';

That bit goes in your theme’s functions.php. Then you just need to add this next bit into your template files wherever you want the tweet to appear.

<?php latest_tweet(); ?>

I’ll go through the functions.php code line by line.

$tweet_feed = fetch_feed('');

This line uses the fetch_feed() function to retrieve the twitter feed. It is returned as a SimplePie object. You’ll need to replace the feed URL with your own, which you can find in the sidebar of your Twitter profile.

$tweet = $tweet_feed->get_items(0, 1);

We just want the latest tweet, so this line uses the get_items() function to extract only the most recent tweet. You could easily change the paramaters here to show more tweets.

echo '<p>' . $tweet[0]->get_date('jS F, G:i') . '</p>';

This line outputs the date and time the tweet was posted using the get_date() function. You can easily change the way that the date is formatted by adjusting the date format string. You can use any of the PHP date format thingies.

echo '<p>' . str_replace('rosshanney: ', '', $tweet[0]->get_content()) . '</p>';

The last line uses the get_content() function to output the tweet itself. I’ve used str_replace() to remove my username from the start of the tweet, but you don’t have to do this.

Not bad for four lines of code :)

As John Kolbert says, WordPress caches the tweet(s) for a while, so this may not be the solution for those who tweet very often.


Update : Shortly after posting I found a nice way to automatically link any @replies, #hashtags or URLs in your tweets, requiring only a small change to the above code. Check out this post.

Update : I’ve extended this a bit more to deal with Twitter not responding, in this post.

No Responses

Leave a Reply