Skip to content

Instantly share code, notes, and snippets.

@michael-martin
Last active September 24, 2020 03:29
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save michael-martin/4578005 to your computer and use it in GitHub Desktop.
Display tweets in WordPress using Twitter API v1.1 - With authentication and a fallback when Twitter is down. Full explanation here: http://www.problogdesign.com/wordpress/authenticate-your-twitter-api-calls-before-march/
<?php
/* REQUIRES: TwitterOAuth
* https://github.com/abraham/twitteroauth/tree/master/twitteroauth
*
* Download and place in a /twitteroauth/ folder in your theme/plugin.
*
*
* Full guide here: http://www.problogdesign.com/wordpress/authenticate-your-twitter-api-calls-before-march/
*
* Uses:
* Twitter API call:
* http://dev.twitter.com/doc/get/statuses/user_timeline
* WP transient API.
* http://www.problogdesign.com/wordpress/use-the-transients-api-to-list-the-latest-commenter/
*/
$numTweets = 3; // Number of tweets to display.
$name = 'problogdesign'; // Username to display tweets from.
$excludeReplies = true; // Leave out @replies
$transName = 'list-tweets'; // Name of value in database.
$cacheTime = 5; // Time in minutes between updates.
$backupName = $transName . '-backup';
// Do we already have saved tweet data? If not, lets get it.
if(false === ($tweets = get_transient($transName) ) ) :
// Get the tweets from Twitter.
include 'twitteroauth/twitteroauth.php';
$connection = new TwitterOAuth(
'xxxxxxxxxxxxxxxxxxxxxx', // Consumer key
'xxxxxxxxxxxxxxxxxxxxxx', // Consumer secret
'xxxxxxxxxxxxxxxxxxxxxx', // Access token
'xxxxxxxxxxxxxxxxxxxxxx' // Access token secret
);
// If excluding replies, we need to fetch more than requested as the
// total is fetched first, and then replies removed.
$totalToFetch = ($excludeReplies) ? max(50, $numTweets * 3) : $numTweets;
$fetchedTweets = $connection->get(
'statuses/user_timeline',
array(
'screen_name' => $name,
'count' => $totalToFetch,
'exclude_replies' => $excludeReplies
)
);
// Did the fetch fail?
if($connection->http_code != 200) :
$tweets = get_option($backupName); // False if there has never been data saved.
else :
// Fetch succeeded.
// Now update the array to store just what we need.
// (Done here instead of PHP doing this for every page load)
$limitToDisplay = min($numTweets, count($fetchedTweets));
for($i = 0; $i < $limitToDisplay; $i++) :
$tweet = $fetchedTweets[$i];
// 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
);
endfor;
// Save our new transient, and update the backup.
set_transient($transName, $tweets, 60 * $cacheTime);
update_option($backupName, $tweets);
endif;
endif;
// Now display the tweets.
?>
<ul id="tweets">
<?php foreach($tweets as $t) : ?>
<li>
<p>
<?php echo $t['text']; ?>
<span class="tweet-time"><?php echo human_time_diff($t['time'], current_time('timestamp')); ?> ago</span>
</p>
</li>
<?php endforeach; ?>
</ul>
@dameer
Copy link

dameer commented Apr 5, 2014

  1. $transName needs to be unique otherwise forget about multiple tweets on the same page!
  2. if(false === ($tweets = get_transient($transName) ) ) is not necessary. For some reason it evaluates TRUE more often than FALSE which results in blank twitts - regardless cache time.

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