The WordPress object cache: wp_cache_set(), groups and persistent backends
WordPress has a key-value cache built in. get_post(), get_option(), get_term(), user and meta lookups all store their results in it, so the same data is read from the database only once per request. Your own code can use the same cache with wp_cache_get() and wp_cache_set(). By default it lives only for one request; with Redis or Memcached as a backend it is kept between requests, and then it saves real database work.
Problem: A plugin runs an expensive query on every page view (counts, statistics, a list built from several tables), and its result changes only a few times a day.
Solution: Wrap the query in wp_cache_get() / wp_cache_set() with your own cache group and an expiration time, and delete the entry with wp_cache_delete() when the data changes. Install a persistent object cache on the server so the result survives between requests, or use transients if you cannot.
Caching a query
<?php
function ha_published_resource_count() {
$count = wp_cache_get( 'resource_count', 'ha_plugin' );
if ( false === $count ) {
global $wpdb;
$count = (int) $wpdb->get_var(
"SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'resource' AND post_status = 'publish'"
);
wp_cache_set( 'resource_count', $count, 'ha_plugin', 5 * MINUTE_IN_SECONDS );
}
return $count;
}
wp_cache_get() returns false when there is no entry. If false can be a real result, use the fourth argument: wp_cache_get( $key, $group, false, $found ) sets $found to true or false.
Deleting stale entries
An expiration time is the fallback; it is better to delete the entry exactly when the data changes:
<?php
add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
if ( 'resource' === $post->post_type && $new_status !== $old_status ) {
wp_cache_delete( 'resource_count', 'ha_plugin' );
}
}, 10, 3 );
add_action( 'deleted_post', function () {
wp_cache_delete( 'resource_count', 'ha_plugin' );
} );
Keys and groups
The group separates your keys from those of core and other plugins, so resource_count in ha_plugin cannot collide with a key of the same name elsewhere. Keys that depend on arguments include them:
<?php
$key = 'user_stats_' . $user_id;
$data = wp_cache_get( $key, 'ha_plugin' );
if ( false === $data ) {
$data = ha_calculate_user_stats( $user_id );
wp_cache_set( $key, $data, 'ha_plugin', HOUR_IN_SECONDS );
}
For many keys that must be invalidated together, add a version number to the key ('stats_v' . $version . '_' . $user_id) and increase the version stored in the cache; the old entries then simply expire.
Persistent backends
The persistent backend is a drop-in file, wp-content/object-cache.php, that a plugin such as Redis Object Cache installs. Check whether one is active:
<?php
if ( wp_using_ext_object_cache() ) {
// Redis, Memcached etc.: entries survive between requests
}
Without it, the cache is an array in PHP memory. That still helps within one request (a function called ten times queries once), but the next page view starts empty. For data that must be kept between requests on any host, use transients (set_transient()): they use the object cache when it is persistent and the options table otherwise.
NOTE: A persistent cache is shared by all requests, so never cache data of one user under a key without the user ID, and never store data in it that only some users may see under a key others can request. And do not cache cheap queries: reading a primary key from MySQL is as fast as reading Redis over the network.