How to Use Object Cache in WordPress for Faster Performance
In WordPress, you use
object cache to store data temporarily in memory, reducing database queries and speeding up your site. Enable it by installing a persistent cache plugin like Redis Object Cache or Memcached, then use functions like wp_cache_set() and wp_cache_get() to store and retrieve cached data.Syntax
WordPress provides simple functions to work with object cache. The main functions are:
wp_cache_set( $key, $data, $group = '', $expire = 0 ): Saves data in cache.wp_cache_get( $key, $group = '', $force = false, &$found = null ): Retrieves cached data.wp_cache_delete( $key, $group = '' ): Removes cached data.
Here, $key is the unique name for your cached item, $group is an optional category, and $expire is how long to keep the cache (0 means forever).
php
wp_cache_set( string $key, mixed $data, string $group = '', int $expire = 0 ): bool wp_cache_get( string $key, string $group = '', bool $force = false, bool &$found = null ): mixed wp_cache_delete( string $key, string $group = '' ): bool
Example
This example shows how to store and retrieve a simple value using WordPress object cache functions. It assumes you have a persistent cache plugin active.
php
<?php // Store data in cache wp_cache_set('my_custom_key', 'Hello, cache!', 'my_group', 3600); // Retrieve data from cache $cached_value = wp_cache_get('my_custom_key', 'my_group'); if ($cached_value !== false) { echo $cached_value; // Outputs: Hello, cache! } else { echo 'Cache miss'; } ?>
Output
Hello, cache!
Common Pitfalls
Many beginners forget that WordPress's default object cache is non-persistent, meaning cached data is lost after each page load unless a persistent cache plugin is installed. Also, using the same $key and $group names for different data can cause conflicts. Avoid caching large objects without expiration to prevent memory bloat.
php
<?php // Wrong: No persistent cache plugin, so cache won't persist between requests wp_cache_set('temp_key', 'temp data'); // Right: Install and activate a persistent cache plugin like Redis or Memcached // Then use wp_cache_set and wp_cache_get as usual wp_cache_set('persistent_key', 'persistent data'); ?>
Quick Reference
| Function | Purpose | Parameters |
|---|---|---|
| wp_cache_set | Store data in cache | $key, $data, $group = '', $expire = 0 |
| wp_cache_get | Retrieve data from cache | $key, $group = '', $force = false, &$found = null |
| wp_cache_delete | Delete cached data | $key, $group = '' |
Key Takeaways
Enable a persistent cache plugin to make object caching effective across page loads.
Use wp_cache_set() and wp_cache_get() to store and retrieve cached data by unique keys.
Avoid key collisions by using meaningful group names for cached items.
Set expiration times to prevent stale or excessive cached data.
Remember WordPress default cache is non-persistent without plugins.