文章页底部那一块评论(评论列表 + 评论框),在模板里只有一行:
<?php comments_template(); ?>
这一行会把主题的 comments.php 引入进来。跟 get_header() 一样,是“搬文件”。
caogenbj 的 single.php 里写的是:
<?php
if ( comments_open() || get_comments_number() ) {
comments_template();
}
?>
两个条件:
comments_open():这篇文章允许评论吗;get_comments_number():已经有评论吗。用“或”连起来的意思是:允许评论,或者已经有评论,就显示评论区。
为什么不直接调?因为如果一篇文章关了评论、也没有评论,就没必要输出一个空的评论区。
如果你没建 comments.php,WordPress 会用内置的默认模板。想自定义样式,就建一个。
一个最简的 comments.php:
<?php if ( post_password_required() ) return; ?>
<div id="comments">
<?php if ( have_comments() ) : ?>
<h2>评论(<?php comments_number(); ?>)</h2>
<ol class="comment-list">
<?php wp_list_comments(); ?>
</ol>
<?php endif; ?>
<?php comment_form(); ?>
</div>
三个关键函数:
have_comments():有没有评论;wp_list_comments():输出评论列表;comment_form():输出评论表单。那一行 post_password_required() 是密码保护文章的判断——加了密码的文章,不应该显示评论。
caogenbj 没有自定义 comments.php,所以用的是 WordPress 默认模板。好处是省事,坏处是样式跟主题不太统一。
如果你想让评论样式跟主题一致,建一个 comments.php,把 wp_list_comments() 的输出结构改成自己的 class。
wp_list_comments() 输出的每一条评论,大概是:
<li class="comment">
<div class="comment-author">头像 + 昵称</div>
<div class="comment-content">评论内容</div>
<div class="reply">回复链接</div>
</li>
想改样式,就针对这些 class 写 CSS。想改结构,用 wp_list_comments( array( 'callback' => 'my_comment' ) ) 自定义回调函数。
WordPress 支持评论嵌套(回复别人的评论)。嵌套的层数在后台“设置 → 讨论 → 评论嵌套”里配。
如果嵌套层数设得深,但主题的 CSS 没处理好,深层的评论会越缩越窄,最后挤成一团。这不是 WordPress 的问题,是 CSS 没写 padding-left 的递进。
一句话记住:comments_template() 引入 comments.php(或默认模板);外面套 comments_open 判断,避免输出空评论区。
下一篇讲分页。