Pixel Envy

Written by Nick Heer.

Display Your Latest Tweet With PHP

Update: These code snippets are all nonfunctional thanks to Twitter’s 1.1 API update.

I get asked, literally some times every so often, the best way to integrate your latest tweet into WordPress. There are a few ways of doing this, but the way I’ve come up with is, I think, pretty nifty.

The first way is using Twitter’s profile widget creator, which displays tweets in a little box which you can change the colours and dimensions of. It’s actually not bad, but it’s a bit generic. It looks the same, despite colour differences, on everyone’s website, and it probably wouldn’t work with a site design similar to mine.

The next solution is using one of Twitter’s other widgets, which are hidden a little on the Twitter site (you need to go into Applications on the Twitter goodies page, not Widgets — it’s linked above for your convenience, though). You can choose between a Flash or HTML widget. The Flash version is similar to the previous widget, in that it looks pretty much the same everywhere, despite colour options. The HTML one is much, much better though. It allows for simple, easy CSS styling. I liked this method so much that I used it on the previous version of nickheer.com

The problem with the HTML widget is that, for whatever reason, it doesn’t seem to work smoothly 100% of the time. I think it’s a Javascript/Wordpress/Safari 4 issue, but it doesn’t matter. In addition, if you want to style it in-depth, it can be a royal pain.

However, I recently found a post on the Smashing Magazine site which described a method for displaying the latest tweet via PHP. This intrigued me, and I implemented it into this revision of the website, and immediately I ran into a huge problem.

This PHP method seems to get easily confused by symbols (<, > and & all seem to be problematic) and links. Bad news for me, since I seem to tweet links quite often. Note that this also applies to @replies, because the username is linked. After much trial-and-error, I think I’ve cracked the perfect way to show your latest tweet(s).

Update: e-sushi posted a much better version of this in the comments. Thanks for the new code.

Click here for the UPDATED code.

The beauty of this code is that it replaces common symbols with their appropriate equivalents, and it parses links perfectly. The bulk of the code is from the Smashing Magazine article, but all of the string replacement code is by me. Please don’t forget to put your Twitter username on line 2.

Update (August 2011): this is another fantastic implementation of a Twitter PHP script. I highly recommend it.