Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.