Created
October 4, 2012 20:34
-
-
Save ericrallen/3836259 to your computer and use it in GitHub Desktop.
Wordpress Twitter Search API simple integration with 2 levels of wp transient caching for fallback
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
<?php //get tweets | |
function get_tweets($s) { | |
$url = 'http://search.twitter.com/search.json?q=' . urlencode($s); | |
//set up var for holding tweets | |
$local_tweets = ''; | |
//check for cache from 5 minutes ago | |
if(get_transient('bodyadorned_tweets_short')) { | |
$local_tweets = get_transient('bodyadorned_tweets_short'); | |
//if it isn't found, try to update tweets | |
} else { | |
$ch = curl_init($url); | |
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
$json = curl_exec ($ch); | |
curl_close ($ch); | |
//if Twitter returned json | |
if($json->results) { | |
$json = json_decode($json); | |
$counter = 0; | |
//loop through it and output tweets | |
foreach ($json->results as $entry) { | |
$counter ++; | |
if($counter < 20) { | |
$text = trim($entry->text); | |
$author = trim($entry->from_user); | |
$id = $entry->id; | |
$local_tweets .= '<article id="tweet-' . $id . '" class="tweet">' . | |
'<p><strong>@' . $author . '</strong><br /> ' . $text . '</p>' . | |
'</article>'; | |
} else { | |
break; | |
} | |
} | |
//reset our 5 min and 1 day caches | |
set_transient('bodyadorned_tweets_long', $local_tweets, 60*60*24*1); | |
set_transient('bodyadorned_tweets_short', $local_tweets, 60*5); | |
//if Twitter didn't respond | |
} else { | |
//check for the 1 day cache | |
if(get_transient('bodyadorned_tweets_long')) { | |
$local_tweets = get_transient('bodyadorned_tweets_long'); | |
//if we can't find that, respond with an error message | |
} else { | |
$local_tweets = '<article class="tweet"><p><strong>No tweets at this time.</strong></p>'; | |
} | |
} | |
} | |
return $local_tweets; | |
} | |
//show tweets | |
$tweets = get_tweets('#hashtag'); | |
echo $tweets; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment