Cache expensive operations with the WordPress Transients API
The Transients API stores cached data with an expiration time. The same set_transient() and get_transient() calls use the wp_options table on a default install and memory (Redis, Memcached) when a persistent object cache is active, without any code changes. Good candidates are remote API responses, heavy WP_Query results with meta queries, computed statistics. The weather example in simple weather without a plugin uses exactly this.
Problem: A dashboard widget shows contributor statistics from the GitHub API. Every admin page load makes an HTTP request: half a second of waiting, rate-limit errors after a few refreshes, and a broken widget when the API is down.
Solution: The cache-aside pattern: read the transient, on a miss call the API and store the result for an hour. Keep the last good response as a fallback for API failures.
The cached function
<?php
function myplugin_get_github_stats( $repo ) {
$key = 'myplugin_gh_' . md5( $repo );
// 1. From the cache
$stats = get_transient( $key );
if ( false !== $stats ) {
return $stats;
}
// 2. From the API
$response = wp_remote_get( 'https://api.github.com/repos/' . $repo . '/contributors', array(
'timeout' => 5,
'headers' => array( 'Accept' => 'application/vnd.github+json' ),
) );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
// 3. The API failed: the last good data, and do not retry for 5 minutes
$fallback = get_option( $key . '_fallback', array() );
set_transient( $key, $fallback, 5 * MINUTE_IN_SECONDS );
return $fallback;
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
$stats = array();
foreach ( array_slice( (array) $body, 0, 10 ) as $contributor ) {
$stats[] = array(
'login' => sanitize_text_field( $contributor['login'] ?? '' ),
'contributions' => absint( $contributor['contributions'] ?? 0 ),
);
}
// 4. Store for an hour, and keep a copy without expiration as the fallback
set_transient( $key, $stats, HOUR_IN_SECONDS );
update_option( $key . '_fallback', $stats, false ); // not autoloaded
return $stats;
}
get_transient() returns false for a missing or expired transient, so do not cache the value false itself: store an empty array instead, as above. Short negative caching on errors (5 minutes) keeps a dead API from being called on every page load.
Invalidate when the data changes
A transient that depends on a post should be deleted when the post changes, not just wait for its expiration:
<?php
function myplugin_get_reading_time( $post_id ) {
$key = 'myplugin_reading_time_' . $post_id;
$time = get_transient( $key );
if ( false === $time ) {
$words = str_word_count( wp_strip_all_tags( get_post_field( 'post_content', $post_id ) ) );
$time = max( 1, (int) ceil( $words / 200 ) );
set_transient( $key, $time, WEEK_IN_SECONDS );
}
return $time;
}
add_action( 'save_post', function ( $post_id ) {
delete_transient( 'myplugin_reading_time_' . $post_id );
} );
Keys and cleanup
- A transient name can be up to 172 characters; prefix it with your plugin (
myplugin_) to avoid collisions. - Expired transients in the database are deleted when they are read, and once a day by WordPress itself (the
delete_expired_transientscron job).wp transient delete --expireddoes it on demand. - To drop all transients of your plugin at once, for example after an update that changes their format, put a version into the key (
myplugin_gh_v2_) instead of deleting rows with SQL: the old ones simply expire. With a persistent object cache they are not inwp_optionsat all.
NOTE: A transient is a cache, not storage: with an object cache it can disappear at any moment (memory pressure, a restart), long before its expiration. Code must always be able to rebuild the value. That is why the fallback above is a normal option, not a transient. Also, a transient set without an expiration is autoloaded with every request, so always pass the third argument.