Adding Twitter feed into WordPress footer

My Name is......and I'm a tweeter...
So, in the midst of re-designing my website I got stumped on what should have been a simple task, pulling back my last tweet from twitter and inserting it into my footer. I spent a couple of hours on and off googling around, but to no avail, so I decided to write my own, here's how I did it.

First, I flicked through twitters API and looked at which would be most work, being lazy, I decided just to take advantage of the GET Search function, nice and simple. All it does is request an atom feed on a particular username, or search term, and you can limit the returns, in simple terms I could send a request to get an atom feed of pmrourkie's (my twitter username) last tweet;

http://search.twitter.com/search.atom?q=from:pmrourkie&rpp=1

If you place that into your url bar you will see the response from twitter.

Now, lets start the code;

$username = "pmrourkie";
$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";

All this is doing is defining the username, and then inserting the defined username in the feed.

Next, we need to create our function and pull out the relevant bits of information from twitters response ;

function recent_tweet($feed) {
$one = explode("", $feed);
$two = explode("", $one[1]);
$tweet = $two[0];
$tweet = str_replace("<", "<", $tweet);      
$tweet = str_replace(">", ">", $tweet);
return $tweet;
}

So, one is going getting all of the information after the tag from twitter, two is saying to stop getting the information after . The next section is naming all of the information from two, or between the and tags, and giving it an array name of "tweet". The next part is just replacing "<" and ">" with the html entities to stop any confusion in the browser.

Now after all of that,the last part returns our tweet.

Finally, the last part, to output the tweet;

$tweetFeed = file_get_contents($feed);
echo recent_tweet($tweetFeed);

Finally, all we need to do it contain this within php tags and we're done;

  
<?php
$username = "pmrourkie";
$feed = "http://search.twitter.com/search.atom?q=from:"; . $username . "&rpp=1";
function recent_tweet($feed) {  
    $one = explode("<content type="html">", $feed);
    $two = explode("</content>", $one[1]);
    $tweet = $two[0];
    $tweet = str_replace("&lt;", "<", $tweet);     
    $tweet = str_replace("&gt;", ">", $tweet);
return $tweet;  
}
$tweetFeed = file_get_contents($feed);
echo recent_tweet($tweetFeed);  
?>

Now, just place this in your wordpress footer and hey-presto!

Show Comments