函数文档

update_comment_cache()

💡 云策文档标注

概述

update_comment_cache() 函数用于更新指定评论的缓存,将评论对象添加到缓存中,并可选择是否更新评论元数据缓存。

关键要点

  • 函数接受一个评论对象数组作为必需参数,可选参数控制是否更新评论元数据缓存,默认值为 true。
  • 如果评论 ID 已存在于缓存中,则不会重复更新,使用评论 ID 作为键添加到缓存组。
  • 内部使用 wp_cache_add_multiple() 批量添加缓存,并在需要时调用 update_meta_cache() 更新元数据。

代码示例

function update_comment_cache( $comments, $update_meta_cache = true ) {
	$data = array();
	foreach ( (array) $comments as $comment ) {
		$data[ $comment->comment_ID ] = $comment;
	}
	wp_cache_add_multiple( $data, 'comment' );

	if ( $update_meta_cache ) {
		// Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
		$comment_ids = array();
		foreach ( $comments as $comment ) {
			$comment_ids[] = $comment->comment_ID;
		}
		update_meta_cache( 'comment', $comment_ids );
	}
}

注意事项

  • 函数从 WordPress 2.3.0 版本引入,4.4.0 版本增加了 $update_meta_cache 参数。
  • 相关函数包括 wp_cache_add_multiple() 和 update_meta_cache(),用于缓存操作和元数据更新。
  • 在传递引用时,避免使用 wp_list_pluck() 来提取评论 ID,以确保代码稳定性。

📄 原文内容

Updates the comment cache of given comments.

Description

Will add the comments in $comments to the cache. If comment ID already exists in the comment cache then it will not be updated. The comment is added to the cache using the comment group with the key using the ID of the comments.

Parameters

$commentsWP_Comment[]required
Array of comment objects
$update_meta_cachebooloptional
Whether to update commentmeta cache.

Default:true

Source

function update_comment_cache( $comments, $update_meta_cache = true ) {
	$data = array();
	foreach ( (array) $comments as $comment ) {
		$data[ $comment->comment_ID ] = $comment;
	}
	wp_cache_add_multiple( $data, 'comment' );

	if ( $update_meta_cache ) {
		// Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
		$comment_ids = array();
		foreach ( $comments as $comment ) {
			$comment_ids[] = $comment->comment_ID;
		}
		update_meta_cache( 'comment', $comment_ids );
	}
}

Changelog

Version Description
4.4.0 Introduced the $update_meta_cache parameter.
2.3.0 Introduced.