Display the Latest Tweet on the WordPress Site

Display the Latest Tweet on the WordPress Site

To display the latest tweet anywhere on the WordPress site, including the header, sidebar, footer, or even the main content area, a simple PHP snippet can be used. This code is entirely self-contained, and can be placed directly into a template file. Here’s how it looks:

< ?php $username = "YourTwitterUsername"; // Put your username here. $prefix = "My Latest Tweet"; // Any text that goes before the tweet itself. $suffix = ""; // Any text that should be placed directly after the tweet. $feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=1";function parse_feed($feed) { $stepOne = explode("“, $feed);
$stepTwo = explode(“”, $stepOne[1]);
$tweet = $stepTwo[0];
$tweet = str_replace(“<“, “< ", $tweet); $tweet = str_replace(">", ">“, $tweet);
return $tweet;
}

$twitterFeed = file_get_contents($feed);
echo stripslashes($prefix) . parse_feed($twitterFeed) . stripslashes($suffix);
?>

The PHP snippet above uses the built-in RSS parsing engine that ships with WordPress. It uses the “username” variable to read an account’s RSS feed, and posts the latest tweet in that feed to the website. The prefix and suffix areas allow the tweet to be placed into context, all within the self-contained PHP code.