Skip to content

Instantly share code, notes, and snippets.

@PeterBooker
Last active December 21, 2015 07:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PeterBooker/6270538 to your computer and use it in GitHub Desktop.
Save PeterBooker/6270538 to your computer and use it in GitHub Desktop.
Background Caching with Transients Example
<?php
/*
* Background Caching with Transients
* Using BBC News API as an example
*/
function pb_get_news() {
/*
* Get transient and if expired refresh data immediately
*/
if ( false === ( $news = get_transient( 'pb_bbc_news' ) ) ) {
// Uses BBC News API to fetch new data
$news = pb_refresh_news();
}
/*
* Check if News has soft expired, if so run refresh after page load.
*/
elseif ( $news->expiry < time() ) {
// Add 60 seconds to soft expire, to stop other threads trying to update it at the same time.
$news->expiry = ( time() + 60 );
/*
* Update soft expire time.
*/
set_transient( 'pb_bbc_news', $news, 24 * HOUR_IN_SECONDS );
// Set the refresh function to run just before PHP shutsdown.
add_action( 'shutdown', 'pb_refresh_news' );
}
return $news;
}
/*
* Refreshes the Transient data.
*/
function pb_refresh_news() {
// Make HTTP request to BBC News API.
$response = wp_remote_request( 'http://api.bbcnews.appengine.co.uk/stories/headlines' );
// Response is in JSON format, so decode it.
$news = json_decode( $response['body'] );
// Add custom expiry time
// MINUTE_IN_SECONDS and the other similar constants are all included in WordPress.
$news->expiry = time() + ( 5 * MINUTE_IN_SECONDS );
// Set transient with latest News data
set_transient( 'pb_bbc_news', $news, 24 * HOUR_IN_SECONDS );
return $news;
}
/*
* Display BBC News Headlines
*/
function pb_display_news() {
// Get the News data
$headlines = pb_get_news();
?>
<ul class="news-container">
<?php foreach ( $headlines->stories as $headline ) { ?>
<li>
<h3>
<a href="<?php echo $headline->link; ?>" title="<?php echo $headline->title; ?>">
<?php echo $headline->title; ?>
</a>
</h3>
<p>
<img src="<?php echo $headline->thumbnail; ?>" alt="<?php echo $headline->title; ?>" />
<?php echo $headline->description; ?>
</p>
</li>
<?php } ?>
</ul>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment