WordPress at a glance

wp_cache_set() WP 2.0.0

Saves the data to the object cache. If data with this key already exists, it will be overwritten.

The difference between this function and wp_cache_add() is that this function is able to add and overwrite the data, while wp_cache_add() is only able to add new data.

See also:

  • wp_cache_add() — adds a new data to the object cache; does nothing if the cache with this key already exists.
  • wp_cache_get() — retrieves a data from the object cahce.
Works based on: WP_Object_Cache::set()
✈ 1 time = 0.000174s = fast | 50000 times = 1.98s = fast | PHP 7.1.11, WP 4.9.8

No Hooks.

Return

true/false. False on failure, true on success

Usage

wp_cache_set( $key, $data, $group, $expire );
$key(int/string) (required)
The cache key to use for retrieval later.
$data(mixed) (required)
The content (data) to store in the cache.
$group(string)
Where to group the cache contents. Enables the same key to be used across groups.
Default: ''
$expire(int)

When the cache content expires, in seconds.

There is no need to use this parameter if the site does not have a persistent cache plugin installed because, without it, WordPress only keeps the cache for the duration of the page generation, and so this parameter is ignored.

Default: 0 (no expiration)

Examples

#1 Save data to the cache and retrieve it when we need it

Suppose we have made a heavy database query and its result is needed in the different parts of the page. We can save it to the cache and access every time we need it. Thus, we eliminate the need to do the same database query many times for a single page:

$cache_key = 'my_db_result';

// Do a database query and save it to the cache if the there is no cache data with this key:
$my_db_result = wp_cache_get( $cache_key );
if( false === $my_db_result ){
	global $wpdb;
	$my_db_result = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'books'");

	wp_cache_set( $cache_key, $my_db_result );
}

// $my_db_result has the same content as the cache

print_r( $my_db_result );

Notes

  • See: WP_Object_Cache::set()
  • Global. WP_Object_Cache. $wp_object_cache Object cache global instance.

Changelog

Since 2.0.0 Introduced.

Code of wp cache set: wp-includes/cache.php WP 5.2.4

<?php
function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

	return $wp_object_cache->set( $key, $data, $group, (int) $expire );
}

Related Functions

From tag: cache (caching)

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register