Created
June 5, 2014 15:54
-
-
Save leocaseiro/455df1f8e1118cb8a2a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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($tweet_count, $username) { | |
if (empty($username)) | |
return false; | |
$list = get_transient('list_of_tweets'); | |
if (!$list) { | |
return fetch_tweets($tweet_count, $username); | |
} | |
return $list; | |
} | |
function fetch_tweets($tweet_count, $username) | |
{ | |
//loading a JSON using wp_remote_get | |
$list = wp_remote_get('https://api.twitter.com/1.1/statuses/'. $username . '.json?screen_name=twitterapi&count=' . $tweet_count); | |
$list = json_decode($list['body']); | |
//Error on Twitter, if error 215 (Bad Authentication data) create an APP here: https://apps.twitter.com/ | |
if (isset($list->errors)) { | |
//create a fake tweet list, just to use on transient cache | |
$list = array(); | |
$list[0] = new stdClass(); | |
$list[0]->text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'; | |
$list[1] = new stdClass(); | |
$list[1]->text = 'Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s.'; | |
$list[2] = new stdClass(); | |
$list[2]->text = 'Lorem Ipsum is that it has a more-or-less normal distribution of letters.'; | |
$list[3] = new stdClass(); | |
$list[3]->text = 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form.'; | |
$list[3] = new stdClass(); | |
$list[3]->text = 'The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.'; | |
} | |
//Config values for transient cache | |
$values = new stdClass(); | |
$values->username = $username; | |
$values->tweet_count = $tweet_count; | |
$values->list = array(); //each tweet | |
foreach($list as $tweet) { | |
//That is better than use $i++ and compare. Its just subtrain each one until became 0; | |
if ($tweet_count-- === 0) | |
break; | |
$values->list[] = $tweet->text; | |
} | |
//setting the cache using the WP Transient API | |
set_transient('list_of_tweets', $values, 60 * 10); //10 minutes cache | |
return $values; | |
} | |
//Sample Usage: | |
get_tweets(5, 'leocaseiro'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment