Add tweets to WordPress
I’m posting this here for future reference as I’ve had use of it in the past.
<?php
// Include to use built-in SimplePie functionality
// see: http://simplepie.org/wiki/reference/start for usage
include_once(ABSPATH . WPINC . '/feed.php');
add_filter( 'wp_feed_cache_transient_lifetime', create_function( '$a', 'return 3600;' ) );
// Set feed URL
$rss = fetch_feed('https://twitter.com/statuses/user_timeline/YOUR_TWITTER_ID.rss');
// Checks that the object is created correctly
if (!is_wp_error( $rss ) ) :
$maxitems = $rss->get_item_quantity(3);
// Build an array of all the items, starting with element 0 (first element).
$rss_items = $rss->get_items(0, $maxitems);
endif;
?>
<ul id="tweetbox">
<?php
if ($maxitems == 0) {
echo '<li>Twitter unavailable at this time.';
} else {
foreach ( $rss_items as $item ) :
//Fetch the tweet itself
$xtwit = $item->get_description();
//Remove the preceding 'username: '
$xtwit = substr(strstr($xtwit, ': '), 2, strlen($xtwit));
// Convert URLs into hyperlinks
$xtwit = preg_replace("/(http:\/\/)(.*?)\/([\w\.\/\&\=\?\-\,\:\;\#\_\~\%\+]*)/", "<a href=\"\\0\" rel=\"external\">\\0</a>", $xtwit);
// Convert usernames (@) into links
$xtwit = preg_replace("(@([a-zA-Z0-9\_]+))", "<a href=\"http://www.twitter.com/\\1\" rel=\"external\">\\0</a>", $xtwit);
// Convert hash tags (#) to links
$xtwit = preg_replace('/(^|\s)#(\w+)/', '\1<a href="http://search.twitter.com/search?q=%23\2" rel="external">#\2</a>', $xtwit);
//Specifically for non-English tweets, converts UTF-8 into ISO-8859-1
$xtwit = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $xtwit);
?>
<li>
<span class="update"><?php echo $xtwit; ?></span><br />
<span class="date"><abbr class="timeago" title="<?php echo $item->get_date('c'); ?>"><?php echo $item->get_date('c'); ?></abbr></span>
</li>
<?php
endforeach;
unset($rss);
}
?>
</ul>
Note: Use the jQuery timeago plugin to parse PHP date stamps into twiiter like time stamps.
Published on November 15, 2011