Skip to content

Instantly share code, notes, and snippets.

@lhl
Created December 8, 2012 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lhl/4238942 to your computer and use it in GitHub Desktop.
Save lhl/4238942 to your computer and use it in GitHub Desktop.
Get Recent Tweets for WordPress
function get_tweets($num=3) {
// Cached
if($tweets = get_transient('tweets')) {
return $tweets;
}
$url = 'http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=lhl&count=20&exclude_replies=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
$tweets = json_decode($content, 1);
for($i=0; $i<count($tweets); $i++) {
// If unset or otherwise empty
if(!$tweets[$i]) {
continue;
}
// Remove @messages
if($tweets[$i]['text'][0] == '@') {
unset($tweets[$i]);
}
// Link Users
// regex from: http://stackoverflow.com/questions/2304632/regex-for-twitter-username
$tweets[$i]['text'] = preg_replace('/(^|[^@\w])@(\w{1,15})\b/', '$1<a href="https://twitter.com/$2">@$2</a>', $tweets[$i]['text']);
// Replace URLs
foreach($tweets[$i]['entities']['urls'] as $url) {
$tweets[$i]['text'] = str_replace($url['url'], "<a href='{$url['expanded_url']}'>{$url['expanded_url']}</a>", $tweets[$i]['text']);
}
}
// Now lets cut down to $num
$tw = array();
foreach($tweets as $tweet) {
$tw[] = $tweet;
if(count($tw) >= $num) {
break;
}
}
$tweets = $tw;
// Cache for 10 min
set_transient('tweets', $tweets, 60*10);
return $tweets;
}
@lhl
Copy link
Author

lhl commented Dec 8, 2012

Tried a few simple plugins that either were old/broken, pulled from RSS/didn't support Twitter entities (needed for decoding t.co URLs among other things, or were purely widget oriented. There were plugins some huge plugins like Twitter Tools (requires 3rd party OAuthing, wtf) that I didn't try. Maybe there was something that exists, but after a good few minutes searching realized it'd be easier to write what I needed for myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment