函数文档

have_comments()

💡 云策文档标注

概述

have_comments() 函数用于检查当前 WordPress 查询中是否有评论可供循环处理。它依赖于全局 $wp_query 对象,通常在 The Loop 中使用。

关键要点

  • 返回布尔值:如果有评论可用则返回 true,否则返回 false。
  • 依赖全局 $wp_query 对象,需确保其已设置。
  • 警告:在调用 comments_template() 之前,此函数始终返回 false;如需提前检查评论,应使用 get_comments_number()。

代码示例

if ( have_comments() ) {
    echo '<h3 id="comments-title">Comments on ' . get_the_title() . '</h3>';
}

注意事项

  • 函数在 WordPress 2.2.0 版本中引入。
  • 相关函数:WP_Query::have_comments() 用于确定是否有更多评论可用。

📄 原文内容

Determines whether current WordPress query has comments to loop over.

Return

bool True if comments are available, false if no more comments.

More Information

This function relies upon the global $wp_query object to be set – this is usually the case from within The Loop.

Warning: this function will always return “false” until after comments_template() has been called. If you need to check for comments before calling comments_template() , use get_comments_number() instead.

Source

function have_comments() {
	global $wp_query;

	if ( ! isset( $wp_query ) ) {
		return false;
	}

	return $wp_query->have_comments();
}

Changelog

Version Description
2.2.0 Introduced.

User Contributed Notes