Skip to content

Instantly share code, notes, and snippets.

@tollmanz
Created March 3, 2012 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tollmanz/1968124 to your computer and use it in GitHub Desktop.
Save tollmanz/1968124 to your computer and use it in GitHub Desktop.
Get Expired Transient
/**
* Used in front end requests to get the latest Tweet.
*
* @return bool|string
*/
function get_latest_tweet() {
// Attempt to get the transient
if ( $tweet = get_transient( 'my_latest_tweet' ) ) {
return $tweet;
// If it doesn't exist, try grabbing the backedup version in wp_options and reset the transient
} elseif ( $tweet = get_option( 'my_latest_tweet' ) ) {
set_transient( 'my_latest_tweet', $tweet );
return $tweet;
// As a last ditch effort, query for the latest tweet
} else {
if ( false !== ( $tweet = cache_latest_tweet() ) ) {
return $tweet;
} else {
return false;
}
}
}
/**
* Grabs the latest tweet.
*
* This function fires on an hourly interval, but can be called on
* front end requests in the event that the transient or wp_option is
* not available.
*
* @return bool|string
*/
function cache_latest_tweet() {
if ( get_transient( 'retrieving_latest_tweet_lock' ) )
return false;
// Avoid multiple requests
set_transient( 'retrieving_latest_tweet_lock', 1 );
/* Not shown: Make call to Twitter API and assign latest Tweet to $tweet */
// Save as both a transient and an option
set_transient( 'my_latest_tweet', $tweet );
if ( get_option( 'my_latest_tweet' ) )
update_option( 'my_latest_tweet', $tweet );
else
add_option( 'my_latest_tweet', $tweet, '', 'no' );
// Remove the lock
delete_transient( 'retrieving_latest_tweet_lock' );
return $tweet;
}
if ( ! wp_next_scheduled( 'schedule_cache_latest_tweet' ) )
wp_schedule_event( time(), 'hourly', 'schedule_cache_latest_tweet' );
add_action( 'schedule_cache_latest_tweet', 'cache_latest_tweet' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment