函数文档

wp_cache_add()

💡 云策文档标注

概述

wp_cache_add() 是 WordPress 中用于向缓存添加数据的函数,仅在缓存键不存在时执行添加操作。它基于 WP_Object_Cache::add() 方法实现,常用于优化数据检索性能。

关键要点

  • 函数作用:向缓存添加数据,前提是缓存键(key)和组(group)的组合不存在。
  • 参数说明:$key(必需,缓存键)、$data(必需,要缓存的数据)、$group(可选,缓存组,默认为空)、$expire(可选,过期时间,单位为秒,默认为0表示永不过期)。
  • 返回值:成功时返回 true,如果缓存键和组已存在则返回 false。
  • 底层实现:通过全局 $wp_object_cache 调用 WP_Object_Cache::add() 方法。
  • 相关用途:被多个核心函数如 get_option()、WP_Post::get_instance() 等调用,用于缓存数据库查询结果和对象实例。

代码示例

function wp_cache_add( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

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

注意事项

  • 此函数是 WordPress 缓存 API 的一部分,自版本 2.0.0 引入。
  • 使用前需确保缓存系统已正确初始化,通常通过全局对象 $wp_object_cache 访问。
  • 如果缓存键已存在,函数不会覆盖数据,而是返回 false,这有助于避免数据冲突。

📄 原文内容

Adds data to the cache, if the cache key doesn’t already exist.

Description

See also

Parameters

$keyint|stringrequired
The cache key to use for retrieval later.
$datamixedrequired
The data to add to the cache.
$groupstringoptional
The group to add the cache to. Enables the same key to be used across groups. Default empty.
$expireintoptional
When the cache data should expire, in seconds.
Default 0 (no expiration).

Return

bool True on success, false if cache key and group already exist.

Source

function wp_cache_add( $key, $data, $group = '', $expire = 0 ) {
	global $wp_object_cache;

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

Changelog

Version Description
2.0.0 Introduced.