wp_cache_set( int|string $key, mixed $data, string $group = '', int $expire = 0 ): bool
- Since
- 2.0.0
- Source
wp-includes/cache.php:108
Stores a value in the WordPress object cache under a given key and group, always overwriting any existing entry. Unlike wp_cache_add() it does not check whether the key already exists, so it is the right call when you want the newest value to win. Without a persistent object cache plugin the data only lives for the current request, and the $expire argument is honored only by backends that support expiration.
Description
Differs from wp_cache_add() and wp_cache_replace() in that it will always write data.
Compatibility
- WordPress
- since 2.0.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$keyint|string- The cache key to use for retrieval later.
$datamixed- The contents to store in the cache.
$groupstringoptional- Where to group the cache contents. Enables the same key to be used across groups. Default empty.Default:
'' $expireintoptional- When to expire the cache contents, in seconds.
Default 0 (no expiration).Default:0
Return value
bool- True on success, false on failure.
Code examples
Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.
Cache the result of an expensive post query for a limited time
Avoid recomputing a list of post titles on every load by checking the cache first and filling it with wp_cache_set() when it's empty.
$cache_key = 'five_recent_titles';
$cache_group = 'reference_demo';
$titles = wp_cache_get( $cache_key, $cache_group );
if ( false === $titles ) {
$recent_posts = get_posts(
array(
'numberposts' => 5,
'orderby' => 'ID',
'order' => 'ASC',
)
);
$titles = wp_list_pluck( $recent_posts, 'post_title' );
wp_cache_set( $cache_key, $titles, $cache_group, 300 );
echo 'Computed and cached: ';
} else {
echo 'Read from cache: ';
}
print_r( $titles );In the sandbox's default non-persistent cache the stored value only survives for the rest of this same request, so a page reload will always recompute it unless a persistent object cache is active.
Overwrite a cached counter regardless of whether it already exists
Show that wp_cache_set() always writes, so a second call replaces the first value instead of leaving it alone.
$key = 'homepage_hits';
$group = 'reference_demo';
wp_cache_set( $key, 10, $group );
echo 'After first set: ' . esc_html( wp_cache_get( $key, $group ) ) . '<br>';
wp_cache_set( $key, 25, $group );
echo 'After second set: ' . esc_html( wp_cache_get( $key, $group ) );Common problems and fixes · 4
- Why does my cached value disappear on the next page load?
- Why isn't the $expire time actually expiring my cached data?
- Should I use wp_cache_set() or wp_cache_add() to save data?
- I set a value with an empty group, why does it clash with another plugin's key?
Why does my cached value disappear on the next page load?
Why isn't the $expire time actually expiring my cached data?
Should I use wp_cache_set() or wp_cache_add() to save data?
I set a value with an empty group, why does it clash with another plugin's key?
Alternatives and related functions
wp_cache_add- When you want to write a value only if that key doesn't already exist in the group, without overwriting an existing entry.
wp_cache_replace- When you want to update a value only if the key already exists, and do nothing if it doesn't.
wp_cache_get- When you need to read back a value that was previously stored with wp_cache_set().
set_transient- When you need the cached value to reliably survive across requests without depending on a persistent object cache plugin.
Performance profile
How much work a call to wp_cache_set() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Trivial
- Scaling
- Constant
- Instructions
- 13
- Plugin surface
- None
- Called by
- 42
Only touches the object cache, via wp_cache_set().
No loop in the body: the same number of instructions runs whatever you pass in.
Executed per call on PHP 8.5. The body compiles to 13.
Nothing here hands control to plugin code.
42 places in core call this, so the cost is paid more often than your own code shows.
What it touches
- cacheobject cache
wp_cache_set()this function does it
What one call costs · 1 distinct outcome
One number would be a lie: the work depends on which branch runs. These are every distinct cost wp_cache_set() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
| always | 13 | ->set() |
Across PHP versions
Compiles the same on PHP 7.4, 8.1, 8.2, 8.3, 8.4, 8.5 and 8.6-dev: 13 instructions, 13 executed per call, 0 branches. The work does not change between versions.
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Used by · 42
- Twenty_Eleven_Ephemera_Widget::widget()Outputs the HTML for this widget.
- WP_AI_Client_Cache::set()Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
- WP_Customize_Manager::find_changeset_post_id()Finds the changeset post ID for a given changeset UUID.
- WP_Embed::find_oembed_post_id()Finds the oEmbed cache post ID for a given cache key.
- WP_MS_Sites_List_Table::column_users()Handles the users column output.
- WP_Privacy_Requests_Table::get_request_counts()Counts the number of requests for each status.
- WP_Site::get_details()Retrieves the details for this site.
- WP_Textdomain_Registry::get_language_files_from_path()Retrieves translation files from the specified path.
- _get_last_post_time()Gets the timestamp of the last time any post was modified or published.
- _wp_image_editor_choose()Tests which editors are capable of supporting the request.
- add_network_option()Adds a new network option.
- add_option()Adds a new option.
Show all 42
- delete_network_option()Removes a network option by name.
- delete_option()Removes an option by name. Prevents removal of protected WordPress options.
- get_blog_details()Retrieves the details for a blog from the blogs table and blog options.
- get_blog_id_from_url()Gets a blog's numeric ID from its URL.
- get_bookmarks()Retrieves the list of bookmarks.
- get_calendar()Displays calendar with days that have posts as links.
- get_lastcommentmodified()Retrieves the date the last comment was modified.
- get_network_option()Retrieves a network's option value based on the option name.
- get_option()Retrieves an option value based on an option name.
- get_plugins()Checks the plugins directory and retrieve all plugin files with plugin data.
- is_blog_installed()Determines whether WordPress is already installed.
- is_object_in_term()Determines if the given object is associated with any of the given terms.
- set_site_transient()Sets/updates the value of a site transient.
- set_transient()Sets/updates the value of a transient.
- update_network_option()Updates the value of a network option that was already added.
- update_option()Updates the value of an option that was already added.
- wp_cache_set_last_changed()Sets last changed date for the specified cache group to now.
- wp_cache_set_multiple()Sets multiple values to the cache in one call.
- wp_cache_set_salted()Stores salted data in the cache.
- wp_count_attachments()Counts number of attachments for the mime type(s).
- wp_count_comments()Retrieves the total comment counts for the whole site or a single post.
- wp_count_posts()Counts number of posts of a post type and if user has permissions to view.
- wp_get_global_settings()Gets the settings resulting of merging core, theme, and user data.
- wp_get_global_styles_custom_css()Gets the global styles custom CSS from theme.json.
- wp_get_global_styles_svg_filters()Returns a string containing the SVGs to be referenced as filters (duotone).
- wp_get_global_stylesheet()Returns the stylesheet resulting of merging core, theme, and user data.
- wp_get_theme_data_template_parts()Returns the metadata for the template parts defined by the theme.
- wp_prime_network_option_caches()Primes specific network options into the cache with a single database query.
- wp_prime_option_caches()Primes specific options into the cache with a single database query.
- wp_set_option_autoload_values()Sets the autoload values for multiple options in the database.
Source code
function wp_cache_set( $key, $data, $group = '', $expire = 0 ) { global $wp_object_cache; return $wp_object_cache->set( $key, $data, $group, (int) $expire );}Changelog
Introduced in 2.0.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 7.1.0 tag, from
src/wp-includes/cache.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.