clean_blog_cache()
云策文档标注
概述
clean_blog_cache() 函数用于清理指定站点的缓存数据,包括站点对象、站点详情、博客详情等缓存条目。它通过 wp_cache_delete() 删除多个缓存组中的相关键值,并触发相关 Hook 以通知其他组件。
关键要点
- 函数接受一个必需参数 $blog,可以是 WP_Site 对象或站点 ID,用于指定要清理缓存的站点。
- 在清理缓存前,会检查全局变量 $_wp_suspend_cache_invalidation 是否设置,若设置则直接返回,避免无效操作。
- 如果 $blog 为空,函数会提前返回;如果 $blog 是 ID 但站点不存在,会创建一个临时的 WP_Site 对象以确保缓存清理能进行。
- 清理的缓存包括 'sites'、'site-details'、'blog-details'、'blog-lookup'、'blog-id-cache' 和 'blog_meta' 等组中的相关条目。
- 函数触发 clean_site_cache 动作,传递站点 ID、站点对象和域名路径的 MD5 哈希值作为参数,供其他插件或主题响应。
- 还调用 wp_cache_set_sites_last_changed() 更新 'sites' 缓存组的最后更改时间,并触发已弃用的 refresh_blog_details 动作(自 4.9.0 起建议使用 clean_site_cache)。
代码示例
// 示例:清理 ID 为 2 的站点缓存
clean_blog_cache( 2 );
// 示例:清理 WP_Site 对象对应的站点缓存
$site = get_site( 3 );
if ( $site ) {
clean_blog_cache( $site );
}注意事项
- 在调用此函数前,确保站点数据有效,以避免不必要的错误或性能开销。
- 注意 clean_site_cache 动作的触发时机,可用于在缓存清理后执行自定义逻辑。
- refresh_blog_details 动作已弃用,新代码应使用 clean_site_cache 替代。
原文内容
Clean the blog cache
Parameters
$blogWP_Site|intrequired-
The site object or ID to be cleared from cache.
Source
function clean_blog_cache( $blog ) {
global $_wp_suspend_cache_invalidation;
if ( ! empty( $_wp_suspend_cache_invalidation ) ) {
return;
}
if ( empty( $blog ) ) {
return;
}
$blog_id = $blog;
$blog = get_site( $blog_id );
if ( ! $blog ) {
if ( ! is_numeric( $blog_id ) ) {
return;
}
// Make sure a WP_Site object exists even when the site has been deleted.
$blog = new WP_Site(
(object) array(
'blog_id' => $blog_id,
'domain' => null,
'path' => null,
)
);
}
$blog_id = $blog->blog_id;
$domain_path_key = md5( $blog->domain . $blog->path );
wp_cache_delete( $blog_id, 'sites' );
wp_cache_delete( $blog_id, 'site-details' );
wp_cache_delete( $blog_id, 'blog-details' );
wp_cache_delete( $blog_id . 'short', 'blog-details' );
wp_cache_delete( $domain_path_key, 'blog-lookup' );
wp_cache_delete( $domain_path_key, 'blog-id-cache' );
wp_cache_delete( $blog_id, 'blog_meta' );
/**
* Fires immediately after a site has been removed from the object cache.
*
* @since 4.6.0
*
* @param string $id Site ID as a numeric string.
* @param WP_Site $blog Site object.
* @param string $domain_path_key md5 hash of domain and path.
*/
do_action( 'clean_site_cache', $blog_id, $blog, $domain_path_key );
wp_cache_set_sites_last_changed();
/**
* Fires after the blog details cache is cleared.
*
* @since 3.4.0
* @deprecated 4.9.0 Use 'clean_site_cache' instead.
*
* @param int $blog_id Blog ID.
*/
do_action_deprecated( 'refresh_blog_details', array( $blog_id ), '4.9.0', 'clean_site_cache' );
}
Hooks
- do_action( ‘clean_site_cache’, string $id, WP_Site $blog, string $domain_path_key )
-
Fires immediately after a site has been removed from the object cache.
- do_action_deprecated( ‘refresh_blog_details’, int $blog_id )
-
Fires after the blog details cache is cleared.
Changelog
| Version | Description |
|---|---|
| 3.5.0 | Introduced. |