WordPress Transient Cache Pattern
Revision History
No revision history recorded yet.
<?php
/**
* Generic transient cache wrapper.
*
* @param string $key Cache key (will be prefixed).
* @param callable $callback Produces the value when cache misses.
* @param int $ttl Time-to-live in seconds. Default 1 hour.
*
* @return mixed
*/
function cached( string $key, callable $callback, int $ttl = HOUR_IN_SECONDS ) {
$cache_key = 'my_plugin_' . md5( $key );
$cached = get_transient( $cache_key );
if ( false !== $cached ) {
return $cached;
}
$value = $callback();
if ( ! is_wp_error( $value ) ) {
set_transient( $cache_key, $value, $ttl );
}
return $value;
}
// Usage
$posts = cached( 'front_page_posts', function () {
return get_posts( [
'post_status' => 'publish',
'numberposts' => 10,
'orderby' => 'date',
] );
}, 15 * MINUTE_IN_SECONDS );