_prime_post_parent_id_caches()
云策文档标注
概述
_prime_post_parent_id_caches() 函数用于预缓存多个文章对象的父ID,以提高性能。它通过检查缓存状态,对未缓存的文章ID从数据库批量查询并存储到缓存中。
关键要点
- 函数接受一个整数数组参数 $ids,表示文章ID列表,用于预缓存父ID。
- 内部使用 wp_cache_get_multiple() 检查缓存,对未命中的ID通过 wpdb::get_results() 从数据库查询,并用 wp_cache_add_multiple() 批量添加缓存。
- 函数包含ID验证和去重处理,确保高效性和数据一致性。
代码示例
function _prime_post_parent_id_caches( array $ids ) {
global $wpdb;
$ids = array_filter( $ids, '_validate_cache_id' );
$ids = array_unique( array_map( 'intval', $ids ), SORT_NUMERIC );
if ( empty( $ids ) ) {
return;
}
$cache_keys = array();
foreach ( $ids as $id ) {
$cache_keys[ $id ] = 'post_parent:' . (string) $id;
}
$cached_data = wp_cache_get_multiple( array_values( $cache_keys ), 'posts' );
$non_cached_ids = array();
foreach ( $cache_keys as $id => $cache_key ) {
if ( false === $cached_data[ $cache_key ] ) {
$non_cached_ids[] = $id;
}
}
if ( ! empty( $non_cached_ids ) ) {
$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.ID, $wpdb->posts.post_parent FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
if ( $fresh_posts ) {
$post_parent_data = array();
foreach ( $fresh_posts as $fresh_post ) {
$post_parent_data[ 'post_parent:' . (string) $fresh_post->ID ] = (int) $fresh_post->post_parent;
}
wp_cache_add_multiple( $post_parent_data, 'posts' );
}
}
}注意事项
- 函数在 WordPress 6.4.0 版本中引入,主要用于内部优化,如 WP_Query::get_posts() 中调用。
- 依赖 _validate_cache_id() 函数进行ID验证,确保缓存键的有效性。
- 缓存键格式为 'post_parent:' 后接文章ID字符串,存储在 'posts' 缓存组中。
原文内容
Prime the cache containing the parent ID of various post objects.
Parameters
$idsint[]required-
ID list.
Source
function _prime_post_parent_id_caches( array $ids ) {
global $wpdb;
$ids = array_filter( $ids, '_validate_cache_id' );
$ids = array_unique( array_map( 'intval', $ids ), SORT_NUMERIC );
if ( empty( $ids ) ) {
return;
}
$cache_keys = array();
foreach ( $ids as $id ) {
$cache_keys[ $id ] = 'post_parent:' . (string) $id;
}
$cached_data = wp_cache_get_multiple( array_values( $cache_keys ), 'posts' );
$non_cached_ids = array();
foreach ( $cache_keys as $id => $cache_key ) {
if ( false === $cached_data[ $cache_key ] ) {
$non_cached_ids[] = $id;
}
}
if ( ! empty( $non_cached_ids ) ) {
$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.ID, $wpdb->posts.post_parent FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );
if ( $fresh_posts ) {
$post_parent_data = array();
foreach ( $fresh_posts as $fresh_post ) {
$post_parent_data[ 'post_parent:' . (string) $fresh_post->ID ] = (int) $fresh_post->post_parent;
}
wp_cache_add_multiple( $post_parent_data, 'posts' );
}
}
}
Changelog
| Version | Description |
|---|---|
| 6.4.0 | Introduced. |