WordPress Transient Cache Pattern

by Jason Chaffetz March 12, 2026 Public
9 views Raw Download Revisions (v1)

Revision History

No revision history recorded yet.

transient-cache.php php Raw
<?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 );
Skip to toolbar