wp_queue_posts_for_term_meta_lazyload()
云策文档标注
概述
wp_queue_posts_for_term_meta_lazyload() 函数用于为文章队列化延迟加载术语元数据,通过处理 WP_Post 对象数组,提取相关术语 ID 并调用 wp_lazyload_term_meta() 实现优化性能。
关键要点
- 函数接受一个必需的参数 $posts,类型为 WP_Post[],表示 WP_Post 对象数组。
- 内部逻辑遍历文章数组,获取每篇文章类型的分类法,并收集文章 ID 到分类法映射。
- 使用 wp_cache_get_multiple() 从缓存中获取术语 ID,处理兼容性情况(如插件可能缓存对象而非 ID)。
- 最终调用 wp_lazyload_term_meta() 延迟加载术语元数据,减少数据库查询。
- 该函数自 WordPress 4.5.0 版本引入,常用于 WP_Query::get_posts() 等场景。
代码示例
function wp_queue_posts_for_term_meta_lazyload( $posts ) {
$post_type_taxonomies = array();
$prime_post_terms = array();
foreach ( $posts as $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
continue;
}
if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
$post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
}
foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
$prime_post_terms[ $taxonomy ][] = $post->ID;
}
}
$term_ids = array();
if ( $prime_post_terms ) {
foreach ( $prime_post_terms as $taxonomy => $post_ids ) {
$cached_term_ids = wp_cache_get_multiple( $post_ids, "{$taxonomy}_relationships" );
if ( is_array( $cached_term_ids ) ) {
$cached_term_ids = array_filter( $cached_term_ids );
foreach ( $cached_term_ids as $_term_ids ) {
foreach ( $_term_ids as $term_id ) {
if ( is_numeric( $term_id ) ) {
$term_ids[] = (int) $term_id;
} elseif ( isset( $term_id->term_id ) ) {
$term_ids[] = (int) $term_id->term_id;
}
}
}
}
}
$term_ids = array_unique( $term_ids );
}
wp_lazyload_term_meta( $term_ids );
}注意事项
- 函数仅处理 WP_Post 对象实例,非实例对象会被跳过。
- 依赖于 wp_cache_get_multiple() 和 get_object_taxonomies() 等核心函数,确保缓存机制正常。
- 设计用于性能优化,避免在查询大量文章时重复加载术语元数据。
原文内容
Queues posts for lazy-loading of term meta.
Parameters
Source
function wp_queue_posts_for_term_meta_lazyload( $posts ) {
$post_type_taxonomies = array();
$prime_post_terms = array();
foreach ( $posts as $post ) {
if ( ! ( $post instanceof WP_Post ) ) {
continue;
}
if ( ! isset( $post_type_taxonomies[ $post->post_type ] ) ) {
$post_type_taxonomies[ $post->post_type ] = get_object_taxonomies( $post->post_type );
}
foreach ( $post_type_taxonomies[ $post->post_type ] as $taxonomy ) {
$prime_post_terms[ $taxonomy ][] = $post->ID;
}
}
$term_ids = array();
if ( $prime_post_terms ) {
foreach ( $prime_post_terms as $taxonomy => $post_ids ) {
$cached_term_ids = wp_cache_get_multiple( $post_ids, "{$taxonomy}_relationships" );
if ( is_array( $cached_term_ids ) ) {
$cached_term_ids = array_filter( $cached_term_ids );
foreach ( $cached_term_ids as $_term_ids ) {
// Backward compatibility for if a plugin is putting objects into the cache, rather than IDs.
foreach ( $_term_ids as $term_id ) {
if ( is_numeric( $term_id ) ) {
$term_ids[] = (int) $term_id;
} elseif ( isset( $term_id->term_id ) ) {
$term_ids[] = (int) $term_id->term_id;
}
}
}
}
}
$term_ids = array_unique( $term_ids );
}
wp_lazyload_term_meta( $term_ids );
}
Changelog
| Version | Description |
|---|---|
| 4.5.0 | Introduced. |