函数文档

update_post_cache()

💡 云策文档标注

概述

update_post_cache() 函数用于更新 WordPress 中的文章缓存,通过处理传入的文章对象数组,将其添加到缓存中以提高性能。

关键要点

  • 函数接受一个 WP_Post 对象数组作为参数(通过引用传递),用于批量更新缓存。
  • 在缓存前,函数会检查文章对象的 filter 属性,如果不是 'raw' 状态,则使用 sanitize_post() 进行清理。
  • 内部调用 wp_cache_add_multiple() 将处理后的文章数据添加到 'posts' 缓存组中。

代码示例

function update_post_cache( &$posts ) {
    if ( ! $posts ) {
        return;
    }

    $data = array();
    foreach ( $posts as $post ) {
        if ( empty( $post->filter ) || 'raw' !== $post->filter ) {
            $post = sanitize_post( $post, 'raw' );
        }
        $data[ $post->ID ] = $post;
    }
    wp_cache_add_multiple( $data, 'posts' );
}

注意事项

  • 该函数自 WordPress 1.5.1 版本引入,是核心缓存机制的一部分。
  • 相关函数包括 wp_cache_add_multiple()、sanitize_post()、update_post_caches() 等,用于扩展缓存功能。
  • update_page_cache() 是其别名,但已弃用,建议直接使用 update_post_cache()。

📄 原文内容

Updates posts in cache.

Parameters

$postsWP_Post[]required
Array of post objects (passed by reference).

Source

function update_post_cache( &$posts ) {
	if ( ! $posts ) {
		return;
	}

	$data = array();
	foreach ( $posts as $post ) {
		if ( empty( $post->filter ) || 'raw' !== $post->filter ) {
			$post = sanitize_post( $post, 'raw' );
		}
		$data[ $post->ID ] = $post;
	}
	wp_cache_add_multiple( $data, 'posts' );
}

Changelog

Version Description
1.5.1 Introduced.