wp_cache_set()
云策文档标注
概述
wp_cache_set() 是 WordPress 中用于将数据保存到缓存的函数,它总是写入数据,区别于 wp_cache_add() 和 wp_cache_replace()。该函数通过 WP_Object_Cache::set() 实现,返回布尔值表示操作成功与否。
关键要点
- 函数签名:wp_cache_set( $key, $data, $group = '', $expire = 0 ),其中 $key 和 $data 为必填参数,$group 和 $expire 为可选参数。
- 参数说明:$key 是缓存键(整数或字符串),$data 是要存储的数据(任意类型),$group 是缓存分组(字符串,默认为空),$expire 是过期时间(秒数,默认为0表示永不过期)。
- 返回值:成功时返回 true,失败时返回 false。
- 相关函数:与 wp_cache_add() 和 wp_cache_replace() 不同,wp_cache_set() 总是覆盖或写入数据;内部调用 WP_Object_Cache::set()。
- 使用场景:广泛用于 WordPress 核心和插件中,如缓存选项、网络选项、主题数据等,以提高性能。
代码示例
function prefix_get_post_count( $post_status = 'publish' ) {
$cache_key = 'prefix_post_count_'. $post_status;
$_posts = wp_cache_get( $cache_key );
if ( false === $_posts ) {
$_posts = $wpdb->get_var(
$wpdb->prepare(
"SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = %s",
$post_status
));
wp_cache_set( $cache_key, $_posts );
}
return $_posts;
}注意事项
- 该函数依赖于对象缓存(object cache),如果服务器未配置对象缓存,建议使用 transient 函数(如 set_transient())以获得更广泛的兼容性,因为 transients 也存储在对象缓存中。
- 缓存第三方 API 响应时,无论同步或异步请求,都应使用 wp_cache_set() 来避免依赖不可靠的外部响应,从而优化站点加载时间。
原文内容
Saves the data to the cache.
Description
Differs from wp_cache_add() and wp_cache_replace() in that it will always write data.
See also
Parameters
$keyint|stringrequired-
The cache key to use for retrieval later.
$datamixedrequired-
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.
$expireintoptional-
When to expire the cache contents, in seconds.
Default 0 (no expiration).
Source
function wp_cache_set( $key, $data, $group = '', $expire = 0 ) {
global $wp_object_cache;
return $wp_object_cache->set( $key, $data, $group, (int) $expire );
}
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 3 content
Mayeenul Islam
function prefix_get_post_count( $post_status = 'publish' ) { $cache_key = 'prefix_post_count_'. $post_status; $_posts = wp_cache_get( $cache_key ); if ( false === $_posts ) { $_posts = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = %s", $post_status )); wp_cache_set( $cache_key, $_posts ); } return $_posts; }Skip to note 4 content
Mahdi Yazdani
Requests made to third-party endpoints should be cached, regardless of being synchronous or asynchronous. Not doing so will result in your site’s load time depending on an unreliable API response!
/** * Retrieve posts from another blog and cache the response body. * * @return string Body of the response. Empty string if no body or incorrect parameter given. */ function wpdocs_get_posts_from_other_blog() { $posts = wp_cache_get( 'wpdocs_other_blog_posts' ); if ( false === $posts ) { $request = wp_remote_get( 'https://jsonplaceholder.typicode.com/posts' ); $posts = wp_remote_retrieve_body( $request ); wp_cache_set( 'wpdocs_other_blog_posts', $posts, '', HOUR_IN_SECONDS ); } return $posts; }