函数文档

wp_defer_comment_counting()

💡 云策文档标注

概述

wp_defer_comment_counting() 函数用于控制是否延迟评论计数更新。当设置为 true 时,所有文章的评论计数将暂不更新,直到设置为 false 时自动批量更新。

关键要点

  • 函数接受一个可选的布尔参数 $defer,默认值为 null,用于设置或获取延迟状态
  • 当 $defer 设置为 true 时,评论计数更新被延迟,避免频繁调用 wp_update_comment_count()
  • 当 $defer 设置为 false 时,自动触发所有延迟的评论计数更新,无需手动调用 wp_update_comment_count()
  • 函数返回当前的延迟状态(布尔值),便于开发者检查
  • 内部使用静态变量 $_defer 存储状态,确保跨调用一致性
  • 常用于批量操作(如删除文章或附件)时优化性能,减少数据库查询

代码示例

function wp_defer_comment_counting( $defer = null ) {
	static $_defer = false;

	if ( is_bool( $defer ) ) {
		$_defer = $defer;
		// Flush any deferred counts.
		if ( ! $defer ) {
			wp_update_comment_count( null, true );
		}
	}

	return $_defer;
}

注意事项

  • 参数 $defer 为可选,如果传入布尔值则设置延迟状态,否则返回当前状态
  • 延迟状态下,评论计数不会实时更新,需在适当时候设置为 false 以同步数据
  • 与 wp_update_comment_count() 函数配合使用,后者在延迟结束时自动调用
  • 自 WordPress 2.5.0 版本引入,兼容性良好

📄 原文内容

Determines whether to defer comment counting.

Description

When setting $defer to true, all post comment counts will not be updated until $defer is set to false. When $defer is set to false, then all previously deferred updated post comment counts will then be automatically updated without having to call wp_update_comment_count() after.

Parameters

$deferbooloptional

Default:null

Return

bool

Source

function wp_defer_comment_counting( $defer = null ) {
	static $_defer = false;

	if ( is_bool( $defer ) ) {
		$_defer = $defer;
		// Flush any deferred counts.
		if ( ! $defer ) {
			wp_update_comment_count( null, true );
		}
	}

	return $_defer;
}

Changelog

Version Description
2.5.0 Introduced.