Skip to content

Instantly share code, notes, and snippets.

@johnregan3
Last active December 26, 2018 15:07
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 johnregan3/ee6c5e25693f3d8aec1faf513292e1fd to your computer and use it in GitHub Desktop.
Save johnregan3/ee6c5e25693f3d8aec1faf513292e1fd to your computer and use it in GitHub Desktop.
WordPress Transients Tutorial, Part 1
<?php
/**
* Get News posts.
*
* This is from a tutorial found here:
* @link https://johnregan3.wordpress.com/how-to-improve-wordpress-load-times-using-transients
*
* @since 1.0.0
* @uses jr3_news_query
*
* @return array Array of news posts, else an empty array.
*/
function jr3_get_news() {
$output = get_transient( 'jr3_news' );
/*
* Side note:
* When an empty array is possible
* (like if a stored array of posts is empty because
* none were found), don't do the typical "! empty()" check.
*
* If the transient is not found, it will return false.
*/
if ( ( false !== $output ) && ( is_array( $output ) ) ) {
// Return the array stored in the transient.
return $output;
}
// Imaginary function to fetch data.
$results = jr3_news_query();
if ( is_array( $results ) ) {
// Set our transient to expire in one hour.
set_transient( 'jr3_news', $results, HOUR_IN_SECONDS );
return $results;
}
// At a minimum, return an empty array.
return array();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment