update_post_caches()
云策文档标注
概述
update_post_caches() 函数用于批量更新文章对象的缓存,包括文章、分类和元数据缓存,以提高查询性能。
关键要点
- 函数接受一个文章对象数组(通过引用传递),可选参数包括文章类型、是否更新分类缓存和元数据缓存。
- 内部调用 update_post_cache()、update_object_term_cache() 和 update_postmeta_cache() 来分别处理不同缓存类型。
- 适用于优化 WP_Query 等场景,避免多次数据库查询。
代码示例
update_post_caches( $posts, $post_type, $update_term_cache, $update_meta_cache );注意事项
- 参数 $posts 必须为 WP_Post 对象数组,且通过引用传递以直接修改缓存。
- 默认更新分类和元数据缓存,可通过参数控制以节省资源。
- 函数从 WordPress 1.5.0 版本引入,是核心缓存机制的一部分。
原文内容
Updates post, term, and metadata caches for a list of post objects.
Parameters
$postsWP_Post[]required-
Array of post objects (passed by reference).
$post_typestringoptional-
Post type. Default
'post'. $update_term_cachebooloptional-
Whether to update the term cache.
Default:
true $update_meta_cachebooloptional-
Whether to update the meta cache.
Default:
true
Source
function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
// No point in doing all this work if we didn't match any posts.
if ( ! $posts ) {
return;
}
update_post_cache( $posts );
$post_ids = array();
foreach ( $posts as $post ) {
$post_ids[] = $post->ID;
}
if ( ! $post_type ) {
$post_type = 'any';
}
if ( $update_term_cache ) {
if ( is_array( $post_type ) ) {
$ptypes = $post_type;
} elseif ( 'any' === $post_type ) {
$ptypes = array();
// Just use the post_types in the supplied posts.
foreach ( $posts as $post ) {
$ptypes[] = $post->post_type;
}
$ptypes = array_unique( $ptypes );
} else {
$ptypes = array( $post_type );
}
if ( ! empty( $ptypes ) ) {
update_object_term_cache( $post_ids, $ptypes );
}
}
if ( $update_meta_cache ) {
update_postmeta_cache( $post_ids );
}
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |