WordPress如何根据标签内容调用评论
在WordPress中,如果你想根据标签内容调用评论,你可以使用WordPress的模板标签和条件语句来实现这一功能。下面是一些步骤和示例代码,帮助你根据标签内容显示评论。
1. 使用comments_template()函数
comments_template()函数是WordPress用来显示评论表单和评论列表的主要函数。你可以在模板文件(如single.php、page.php等)中调用此函数。
示例代码:
if (have_comments()) {
comments_template();
} else {
// 没有评论时的内容
echo '<p>暂无评论。</p>';
}
2. 根据特定标签显示评论
如果你想根据特定的标签内容来显示评论,你可以使用get_posts()或get_the_ID()结合条件语句来实现。例如,如果你想在一个帖子中根据某个自定义字段(例如,一个标签或分类)来显示评论,可以这样做:
示例代码:
假设你有一个自定义字段(例如,名为show_comments),你想基于这个字段的值来决定是否显示评论。
// 获取自定义字段的值
$show_comments = get_post_meta(get_the_ID(), 'show_comments', true);
if ($show_comments == 'yes') { // 假设'yes'是你用来决定是否显示评论的值
if (comments_open() || get_comments_number()) { // 检查评论是否开放或有评论存在
comments_template();
} else {
echo '<p>暂无评论。</p>';
}
} else {
echo '<p>评论已关闭。</p>'; // 如果自定义字段不是'yes',则显示此消息
}
3. 使用wp_list_comments()函数自定义评论列表
如果你想要更细致地控制评论的显示方式(例如,只显示某些类型的评论),你可以使用wp_list_comments()函数。这个函数允许你通过参数来过滤评论。
示例代码:
if (have_comments()) {
wp_list_comments(array(
'callback' => 'mytheme_comment', // 自定义回调函数来格式化评论输出
));
} else {
echo '<p>暂无评论。</p>';
}
其中,mytheme_comment是一个自定义的回调函数,用于格式化每条评论的显示方式。你可以在functions.php文件中定义这个函数:
function mytheme_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>">
<div id="comment-<?php comment_ID(); ?>">
<div class="comment-author"><?php echo get_avatar($comment, $size = '48'); ?> <?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link()) ?></div>
<?php if ($comment->comment_approved == '0') : ?>
<em><?php _e('Your comment is awaiting moderation.') ?></em>
<br />
<?php endif; ?>
<div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars(get_comment_link($comment->comment_ID)) ?>"> <?php printf(__('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'), ' ', '') ?></div>
<?php comment_text() ?>
<div class="reply">
<?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
</div>
</div>
<?php
}
通过这些方法,你可以根据标签内容或其他条件灵活地控制WordPress中评论的显示。
提示:AI自动生成,仅供参考
参考 |