函数文档

wp_update_comment_count()

💡 云策文档标注

概述

wp_update_comment_count() 函数用于更新文章的评论计数。它支持延迟处理机制,当评论计数被设置为延迟时,可以将文章ID加入队列,稍后批量更新。

关键要点

  • 函数接受两个参数:$post_id(必需,文章ID)和 $do_deferred(可选,布尔值,默认为 false)。
  • 当 $do_deferred 为 false 且评论计数延迟启用时,文章ID会被添加到静态数组 $_deferred 中,稍后处理。
  • 当 $do_deferred 为 true 时,会处理所有之前延迟的文章ID,并更新当前 $post_id。
  • 返回值为 bool|void:成功时返回 true,失败或文章不存在时返回 false。
  • 相关函数包括 wp_update_comment_count_now() 和 wp_defer_comment_counting()。

代码示例

function wp_update_comment_count( $post_id, $do_deferred = false ) {
	static $_deferred = array();

	if ( empty( $post_id ) && ! $do_deferred ) {
		return false;
	}

	if ( $do_deferred ) {
		$_deferred = array_unique( $_deferred );
		foreach ( $_deferred as $i => $_post_id ) {
			wp_update_comment_count_now( $_post_id );
			unset( $_deferred[ $i ] );
			/** @todo Move this outside of the foreach and reset $_deferred to an array instead */
		}
	}

	if ( wp_defer_comment_counting() ) {
		$_deferred[] = $post_id;
		return true;
	} elseif ( $post_id ) {
		return wp_update_comment_count_now( $post_id );
	}
}

📄 原文内容

Updates the comment count for post(s).

Description

When $do_deferred is false (is by default) and the comments have been set to be deferred, the post_id will be added to a queue, which will be updated at a later date and only updated once per post ID.

If the comments have not be set up to be deferred, then the post will be updated. When $do_deferred is set to true, then all previous deferred post IDs will be updated along with the current $post_id.

See also

Parameters

$post_idint|nullrequired
Post ID.
$do_deferredbooloptional
Whether to process previously deferred post comment counts.

Default:false

Return

bool|void True on success, false on failure or if post with ID does not exist.

Source

function wp_update_comment_count( $post_id, $do_deferred = false ) {
	static $_deferred = array();

	if ( empty( $post_id ) && ! $do_deferred ) {
		return false;
	}

	if ( $do_deferred ) {
		$_deferred = array_unique( $_deferred );
		foreach ( $_deferred as $i => $_post_id ) {
			wp_update_comment_count_now( $_post_id );
			unset( $_deferred[ $i ] );
			/** @todo Move this outside of the foreach and reset $_deferred to an array instead */
		}
	}

	if ( wp_defer_comment_counting() ) {
		$_deferred[] = $post_id;
		return true;
	} elseif ( $post_id ) {
		return wp_update_comment_count_now( $post_id );
	}
}

Changelog

Version Description
2.1.0 Introduced.