Object Cache Pro
Till Krüss

New cache APIs

Sometimes you may wish to retrieve an item from the cache, but also store a value if the item doesn’t exist. The WordPress object cache API makes this quite tedious.

For example, you may wish to retrieve all users from the cache or, if they don’t exist, retrieve them from the database and add them to the cache.

$users = wp_cache_get('users', 'my-plugin');

if ($users === false) {
$users = get_users();

wp_cache_set('users', $users, 'my-plugin', DAY_IN_SECONDS);
}

return $users;

Starting with Object Cache Pro v1.9.1, you may do the same operation using the wp_cache_remember() function in a single line:

$users = wp_cache_remember( 'users', DAY_IN_SECONDS, fn() => get_users(), 'my-plugin' );

// In PHP 7.3 and older:
$users = wp_cache_remember( 'users', DAY_IN_SECONDS, function () {
return get_users();
}, 'my-plugin' );

If the item does not exist in the cache, the Closure passed to wp_cache_remember() will be executed and its result will be stored in the cache.

To store an item forever, you may use the wp_cache_sear() function:

$comments = wp_cache_sear( 'post:1:comments', function () {
return get_comments( [ 'post_id' => 1 ] );
}, 'my-plugin' );

Happy coding!