Here you go:
add_shortcode('latest_tweets', 'latest_tweets');
function latest_tweets($atts){
extract(shortcode_atts(array(
'max' => 5
), $atts));
$twitter_id = esc_attr(strip_tags($atts[0]));
// try to get data from cache to avoid slow page loading or twitter blocking
if (false === ($output = get_transient("latest_tweets_{$twitter_id}"))):
$doc = new DOMDocument();
$feed = "http://twitter.com/statuses/user_timeline/{$twitter_id}.rss";
$doc->load($feed);
$output = "<ul>";
$i = 1;
foreach ($doc->getElementsByTagName('item') as $node) {
$tweet = $node->getElementsByTagName('title')->item(0)->nodeValue;
//if you want to remove the userid before the tweets then uncomment the next line.
//$tweet = substr($tweet, stripos($tweet, ':') + 1);
$tweet = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="https://wordpress.stackexchange.com/questions/5663/">$1</a>', $tweet);
$tweet = preg_replace("/@([0-9a-zA-Z]+)/", "<a href=\"http://twitter.com/$1\">@$1</a>", $tweet);
$output .= "<li>{$tweet}</li>\n";
if($i++ >= $max) break;
}
$output .= "</ul>\n";
set_transient("latest_tweets_{$twitter_id}", $output, 60*10); // 10 minute cache
endif;
return $output;
}
Usage:
[latest_tweets "DarthVader" max=5]
PS: you have some exploit in the code you posted in your question. You should take care of that…
PPS: for people who want to do something like this:
-
use Yahoo Query Language,
requests should be faster
theoretically, and you have less
chances to be limited by the service
you’re requesting data from -
use the JSON format for the data you request
-
use WP’s HTTP API to make external requests