_count_posts_cache_key()
云策文档标注
概述
_count_posts_cache_key() 函数用于生成 wp_count_posts() 的缓存键,基于传入的参数如文章类型和权限设置。
关键要点
- 函数返回一个字符串作为缓存键,用于 wp_count_posts() 的缓存机制。
- 参数 $type 指定文章类型,默认值为 'post'。
- 参数 $perm 指定权限检查,可选 'readable' 或空字符串,默认空。
- 当 $perm 为 'readable' 且用户已登录时,如果用户没有读取私有文章的权限,缓存键会包含用户ID以区分权限。
代码示例
function _count_posts_cache_key( $type = 'post', $perm = '' ) {
$cache_key = 'posts-' . $type;
if ( 'readable' === $perm && is_user_logged_in() ) {
$post_type_object = get_post_type_object( $type );
if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
$cache_key .= '_' . $perm . '_' . get_current_user_id();
}
}
return $cache_key;
}注意事项
- 此函数主要用于内部缓存优化,开发者通常不直接调用,而是通过 wp_count_posts() 间接使用。
- 缓存键的生成考虑了用户权限,确保不同权限用户看到正确的文章计数。
- 自 WordPress 3.9.0 版本引入,相关函数包括 current_user_can()、is_user_logged_in() 等。
原文内容
Returns the cache key for wp_count_posts() based on the passed arguments.
Parameters
$typestringoptional-
Post type to retrieve count Default
'post'. $permstringoptional-
'readable'or empty. Default empty.
Source
function _count_posts_cache_key( $type = 'post', $perm = '' ) {
$cache_key = 'posts-' . $type;
if ( 'readable' === $perm && is_user_logged_in() ) {
$post_type_object = get_post_type_object( $type );
if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
$cache_key .= '_' . $perm . '_' . get_current_user_id();
}
}
return $cache_key;
}
Changelog
| Version | Description |
|---|---|
| 3.9.0 | Introduced. |