Object Caching in WordPress

Summary: Learning about the Object Caching in WordPress and its different functions.

The WordPress Object Cache is used to save on trips to the database. The Object Cache stores all of the cache data to memory and makes the cache contents available by using a key, which is used to name and later retrieve the cache contents.

The Object Cache can be replaced by other caching mechanisms by placing files in the wp-content folder which is looked at in wp-settings. If that file exists, then this file will not be included.

Object caching involves storing the results of expensive or repetitive queries to the database in memory (RAM). When the same query or data is requested again the cached version is served significantly speeding up data retrieval. WordPress has a built-in object caching system that uses PHP arrays to store cached data during a single page load. This cache is cleared at the end of the page load meaning it doesn’t persist across requests.

WordPress has a non-persistent object cache by default which means it only caches data for the duration of a single page load. Once the request is completed, the cache is cleared.

WordPress uses the $wp_object_cache global object to store cached data during a request. Functions like wp_cache_set(), wp_cache_get(), wp_cache_delete(), and wp_cache_flush() are used to interact with the cache.

wp_cache_set()

The wp_cache_set() function stores data in the cache.

wp_cache_set($key, $data, $group = '', $expire = 0);
  • $key (string, required):
    This is a unique identifier for the cached data. It serves as a reference to retrieve or delete the data later. It’s crucial to choose a unique and descriptive key to avoid conflicts with other cached data.
  • $data (mixed, required):
    The actual data to be stored in the cache. This can be any type of PHP data, such as a string, array, object, etc.
  • $group (string, optional):
    This is an optional parameter that allows us to group related cache entries together. Grouping helps in managing cache entries more effectively and avoids naming conflicts across different types of data. For example, we might use 'users' for user-related data or 'posts' for post-related data. If not specified, the default group is an empty string ('').
  • $expire (int, optional):
    The expiration time for the cached data in seconds. This determines how long the data should remain in the cache before it is considered stale and removed. If set to 0 (the default value), the cached data will not expire.
$cache_key = 'my_custom_data';  
$data_to_cache = 'Hello, World!'; 
$cache_group = 'my_group';
$expiration = 3000; 

wp_cache_set($cache_key, $data_to_cache, $cache_group, $expiration);

wp_cache_get()

The wp_cache_get() function retrieves data from the cache.

wp_cache_get($key, $group = '', $force = false, &$found = null);
  • $key (string, required):
    The unique identifier used when the data was cached. This key should match the one used with wp_cache_set() to store the data. It tells WordPress which piece of data we want to retrieve from the cache.
  • $group (string, optional):
    The group for the cached data. This should match the group used when the data was set in the cache. If not specified, it defaults to an empty string (''). Groups help in organizing and differentiating data, making it easier to manage.
  • $force (bool, optional):
    If set to true, this parameter forces the function to return the cache value even if it is considered stale or expired. By default, this is set to false, meaning the function will only return data that is still valid according to its expiration settings.
  • $found (bool, optional, passed by reference):
    A boolean variable passed by reference that will be set to true if the data is found in the cache or false if not. This parameter allows us to determine programmatically whether the cache contained the requested data.
$cache_key = 'my_custom_data'; 
$cache_group = 'my_group'; 

$cached_data = wp_cache_get($cache_key, $cache_group);

if ($cached_data !== false) {
    echo 'Data retrieved from cache: ' . $cached_data;
} else {
    echo 'Data not found in cache.';
}

wp_cache_delete()

The wp_cache_delete() function removes data from the cache.

wp_cache_delete($key, $group = '');
  • $key (string, required):
    The unique identifier for the data to delete from the cache. This should be the same key used when the data was cached with wp_cache_set(). It specifies which cached item we wish to remove.
  • $group (string, optional):
    The group for the cached data. This should match the group used when the data was set in the cache. If not specified, it defaults to an empty string (''). Providing the correct group ensures that the exact data entry is deleted, avoiding accidental deletions of similarly named cache keys in different groups.
$cache_key = 'my_custom_data'; 
$cache_group = 'my_group';

if (wp_cache_delete($cache_key, $cache_group)) {
    echo 'Data deleted from cache.';
} else {
    echo 'Failed to delete data or data not found in cache.';
}

wp_cache_flush()

The wp_cache_flush() function clears all cached data.

wp_cache_flush();
  • No Parameters:
    This function will clear all data in the cache across all groups and keys. It is typically used when we want to completely reset the cache such as during development after major updates or when troubleshooting cache-related issues.

wp_cache_add()

The wp_cache_add() function is similar to wp_cache_set() but it only adds data to the cache if the key does not already exist. If the key exists it will not overwrite the existing data.

wp_cache_add($key, $data, $group = '', $expire = 0);
  • $key (string, required):
    A unique identifier for the cache data. This key is used to check if the data already exists in the cache. If it does, the function will not add the new data.
  • $data (mixed, required):
    The data to cache. This can be any data type such as a string, array, or object.
  • $group (string, optional):
    The group for the cache data. This parameter helps in organizing cached items. If not provided it defaults to an empty string ('').
  • $expire (int, optional):
    The time in seconds for the cache to expire. A value of 0 means the cache does not expire, although it could still be removed if the cache system decides to clear it.
$cache_key = 'custom_data';
$data = 'Hello, World!';
$group = 'my_custom_group';
$expiration = 60;

if (!wp_cache_add($cache_key, $data, $group, $expiration)) {
    echo 'Data already exists in the cache.';
} else {
    echo 'Data added to the cache.';
}

wp_cache_replace()

The wp_cache_replace() function replaces the data in the cache for a given key if the key already exists. If the key does not exist, the function does nothing.

wp_cache_replace($key, $data, $group = '', $expire = 0);
  • $key (string, required):
    The unique identifier for the cache data. This key is used to find the existing cached data to be replaced.
  • $data (mixed, required):
    The new data to store in the cache. This can be any data type, such as a string, array, or object.
  • $group (string, optional):
    The group for the cache data. Used for organizing cached items. If not provided it defaults to an empty string ('').
  • $expire (int, optional):
    The expiration time for the cache data in seconds. A value of 0 means the data does not expire although it could be cleared by the cache system.
$cache_key = 'custom_data';
$new_data = 'Updated data';
$group = 'my_custom_group';
$expiration = 60;

if (wp_cache_replace($cache_key, $new_data, $group, $expiration)) {
    echo 'Cache data replaced successfully.';
} else {
    echo 'Cache data does not exist; no replacement done.';
}

wp_cache_add_global_groups()

The wp_cache_add_global_groups() function designates certain cache groups to be treated as “global” across multiple sites in a multisite WordPress network. This means the cached data for these groups is shared across all sites in the network.

wp_cache_add_global_groups($groups);
  • $groups (array|string, required):
    The cache groups to be treated as global. We can pass a single group name as a string or multiple group names as an array. The groups listed here will have their cache data shared across all sites in a multisite installation.
// Make 'user_sessions' and 'site_options' groups global in a multisite environment
wp_cache_add_global_groups(['user_sessions', 'site_options']);

This function is particularly useful in a multisite WordPress network where we want certain data like user sessions or site-wide settings to be consistent across all sites preventing the need to set or retrieve this data multiple times for each site.

wp_cache_add_non_persistent_groups()

The wp_cache_add_non_persistent_groups() function designates certain cache groups to be non-persistent. This means the data for these groups is not stored persistently and will only be cached for the duration of a single page load.

wp_cache_add_non_persistent_groups($groups);
  • $groups (array|string, required):
    The cache groups to be treated as non-persistent. We can pass a single group name as a string or multiple group names as an array. The groups listed here will have their cache data removed at the end of each page load.
// Make the 'transient_cache' group non-persistent
wp_cache_add_non_persistent_groups('transient_cache');

This function is useful when we have data that should not persist between page loads like transient data that changes frequently or is only relevant for the current request. By designating these groups as non-persistent we ensure that this data does not unnecessarily take up space in persistent storage.

Persistent Object Cache

Unlike the default object cache a persistent object cache retains cached data between different page loads and user sessions. It requires an external caching system such as Memcached, Redis or a similar caching service. By caching data across requests persistent object caching significantly reduces the number of database queries and improves site performance especially on high-traffic sites or those with expensive queries.

«
»

Leave a Reply

Your email address will not be published. Required fields are marked *