函数文档

_prime_post_caches()

💡 云策文档标注

概述

_prime_post_caches() 是 WordPress 核心函数,用于将指定 ID 列表中未缓存的帖子预加载到缓存中,以提高性能。它支持可选地更新元数据和分类法缓存。

关键要点

  • 函数接受帖子 ID 数组作为必需参数,可选参数控制是否更新分类法缓存和元数据缓存,默认均为 true。
  • 内部通过 _get_non_cached_ids() 筛选未缓存的 ID,使用 SQL 查询获取帖子数据,并调用 update_post_cache() 更新缓存。
  • 根据参数设置,可能调用 update_postmeta_cache() 和 update_object_term_cache() 来同步更新相关缓存。
  • 函数自 WordPress 3.4.0 引入,在 6.1.0 版本中不再标记为“私有”,可安全使用。

代码示例

function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
    global $wpdb;

    $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
    if ( ! empty( $non_cached_ids ) ) {
        $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );

        if ( $fresh_posts ) {
            update_post_cache( $fresh_posts );
        }
    }

    if ( $update_meta_cache ) {
        update_postmeta_cache( $ids );
    }

    if ( $update_term_cache ) {
        $post_types = array_map( 'get_post_type', $ids );
        $post_types = array_unique( $post_types );
        update_object_term_cache( $ids, $post_types );
    }
}

注意事项

  • 函数主要用于性能优化,避免在循环中重复查询数据库,建议在批量处理帖子时使用。
  • 参数 $update_term_cache 和 $update_meta_cache 默认为 true,但可根据需要设置为 false 以减少不必要的缓存更新。
  • 相关函数包括 update_post_cache()、update_postmeta_cache() 和 update_object_term_cache(),用于具体缓存操作。

📄 原文内容

Adds any posts from the given IDs to the cache that do not already exist in cache.

Description

See also

Parameters

$idsint[]required
ID list.
$update_term_cachebooloptional
Whether to update the term cache.

Default:true

$update_meta_cachebooloptional
Whether to update the meta cache.

Default:true

Source

function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
	global $wpdb;

	$non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
	if ( ! empty( $non_cached_ids ) ) {
		$fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", implode( ',', $non_cached_ids ) ) );

		if ( $fresh_posts ) {
			// Despite the name, update_post_cache() expects an array rather than a single post.
			update_post_cache( $fresh_posts );
		}
	}

	if ( $update_meta_cache ) {
		update_postmeta_cache( $ids );
	}

	if ( $update_term_cache ) {
		$post_types = array_map( 'get_post_type', $ids );
		$post_types = array_unique( $post_types );
		update_object_term_cache( $ids, $post_types );
	}
}

Changelog

Version Description
6.1.0 This function is no longer marked as “private”.
3.4.0 Introduced.