Skip to content

Instantly share code, notes, and snippets.

@lgarcia
Created January 29, 2012 01:17
Show Gist options
  • Save lgarcia/1696560 to your computer and use it in GitHub Desktop.
Save lgarcia/1696560 to your computer and use it in GitHub Desktop.
JSON Lists of Tweets PHP (transient WP)
<ul id="tweets">
<?php
/*
* JSON list of tweets using:
* http://dev.twitter.com/doc/get/statuses/user_timeline
* Cached using WP transient API.
* http://www.problogdesign.com/wordpress/use-the-transients-api-to-list-the-latest-commenter/
*/
// Configuration.
$numTweets = 3;
$name = 'problogdesign';
$transName = 'list-tweets'; // Name of value in database.
$cacheTime = 5; // Time in minutes between updates.
// Do we already have saved tweet data? If not, lets get it.
if(false === ($tweets = get_transient($transName) ) ) :
// Get the tweets from Twitter.
$json = wp_remote_get("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$name&count=$numTweets");
// Get tweets into an array.
$twitterData = json_decode($json['body'], true);
// Now update the array to store just what we need.
// (Done here instead of PHP doing this for every page load)
foreach ($twitterData as $tweet) :
// Core info.
$name = $tweet['user']['name'];
$permalink = 'http://twitter.com/#!/'. $name .'/status/'. $tweet['id_str'];
/* Alternative image sizes method: http://dev.twitter.com/doc/get/users/profile_image/:screen_name */
$image = $tweet['user']['profile_image_url'];
// Message. Convert links to real links.
$pattern = '/http:(\S)+/';
$replace = '<a href="${0}" target="_blank" rel="nofollow">${0}</a>';
$text = preg_replace($pattern, $replace, $tweet['text']);
// Need to get time in Unix format.
$time = $tweet['created_at'];
$time = date_parse($time);
$uTime = mktime($time['hour'], $time['minute'], $time['second'], $time['month'], $time['day'], $time['year']);
// Now make the new array.
$tweets[] = array(
'text' => $text,
'name' => $name,
'permalink' => $permalink,
'image' => $image,
'time' => $uTime
);
endforeach;
// Save our new transient.
set_transient($transName, $tweets, 60 * $cacheTime);
endif;
// Now display the tweets.
foreach($tweets as $t) : ?>
<li>
<img src="<?php echo $t['image']; ?>" width="48" height="48" alt="" />
<div class="tweet-inner">
<p>
<?php echo $t['name'] . ': '. $t['text']; ?>
<span class="tweet-time"><?php echo human_time_diff($t['time'], current_time('timestamp')); ?> ago</span>
</p>
</div><!-- /tweet-inner -->
</li>
<?php endforeach; ?>
</ul>
<p><a href="http://twitter.com/#!/<?php echo $name; ?>">[ Follow us on Twitter ]</a></p> [feedly mini]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment