Created
December 8, 2012 06:39
-
-
Save lhl/4238942 to your computer and use it in GitHub Desktop.
Get Recent Tweets for WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.