Skip to content

Instantly share code, notes, and snippets.

@wpmark
Last active Nov 5, 2021
Embed
What would you like to do?
An example of caching data using a WordPress transient

Caching WordPress data using Transients - Example

In this simple example we create a function for obtaining data from an external source and caching it for 24 hours. You can use the function hd_get_external_data() to get the data and work with it in your site.

If you want to force a refresh of the cache, you can pass a value of true into the function.

You can place the code into your themes functions.php file or better still in a plugin. If you are placing it in a plugin, remember to use function_exists() when using this. This ensures that the code will fail correctly if the plugin is not active.

<?php
/**
* Gets data for our external source, either from cache or externally.
*
* @param bool $force_refresh True to force getting the data again or false to try and get from cache.
* @return string $external_data The external data to return - in this case a string.
*/
function hd_get_external_data( $force_refresh = false ) {
// get the external data from the cache - a transient in the WP database.
$external_data = get_transient( 'hd_external_data' );
// if no external data is found or we are forcing a refresh, the transient must have expired. Get the data again.
if ( true === $force_refresh || false === $external_data ) {
// grab the external data.
// your method here will be different depending on what data you are getting.
// for this example, it is just a string of text.
$external_data = 'Some string of external data';
// if our call to external data returned something and is not an error.
// you should also check the data is in the correct format here too e.g. string, JSON, integer etc.
if ( ! is_wp_error( $external_data ) && ! empty( $external_data ) {
// now we have the data, before we return it, let's cache it in the transient.
// we set an expire time on the cache of 24 hours. Change to whatever is appropriate here.
set_transient( 'hd_external_data', $external_data, DAY_IN_SECONDS );
}
}
// return the external data for use.
return $external_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment