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.
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. |
Skip to note 2 content
Codex
Basic Example
Example based on Twentyten’s comments.php template: Comments title (and more) is displayed only when comments are available:
<h3 id="comments-title">' . get_the_title() . '</em>' ); ?></h3> // [and more, of course...] <p class="nocomments"></p>