在本教程中,我将向您展示如何显示作者在文章评论部分中发布的评论总数量计数,而不需要插件,如下图所示:

教程:如何在WordPress中显示作者的评论计数

The WordPress Toolbox
Unlimited Downloads: 500,000+ WordPress Themes, Plugins, Templates & Design Assets

教程:如何在WordPress中显示作者的评论计数

DOWNLOAD NOW

如上图显示,每当有人对任何文章发表评论时,作者的评论总数将显示在他/她的姓名旁边。这是一个非常实用的功能。喜欢折腾的朋友可以试试。

以下是代码的功能:

  • 只有核准的评论才算在内。 待处理(和垃圾)评论不计算在内。
  • 测试代码在WordPress版本3.8.0上正常工作,但它将适用于早期版本。
  • 代码根据他们的电子邮件地址作者的评论。 即使未注册的用户评论也算在内。

这里是如何显示作者的评论数量。

步骤1:计数作者评论核心代码,放在functions.php里面

打开位于主题文件夹中的functions.php文件,并添加(复制和粘贴)以下代码。 保存文件并将其上传到服务器。

<?php /************************************
*@Author: 99839
* @Websites: www.iesay.com/
************************************/
function bac_comment_count_per_user() { global $wpdb; $comment_count = $wpdb->get_var(
'SELECT COUNT(comment_ID) FROM '. $wpdb->comments. '
WHERE comment_author_email = "' . get_comment_author_email() .'"
AND comment_approved = "1"
AND comment_type NOT IN ("pingback", "trackback")'
);

//Discriminate between singular and plural.
if ( $comment_count == 1) {
echo ' (1 comment)';
}
else {
echo ' (' . $comment_count . ' comments)';
}
}
?>

步骤2:显示评论计数

将步骤1的代码添加到主题的functions.php之后,现在需要显示评论计数。要做到这一点,有3种情况。 这一切都取决于你使用的主题:
打开你的主题的comments.php文件。 如果在这个文件中你发现...

1、具有回调参数的wp_list_comments()函数。 就像是:

<?php wp_list_comments('callback=mytheme_comment'); ?>

那么在这种情况下,您需要编辑位于主题的functions.php文件中的mytheme_comment函数。

2、没有回调的wp_list_comments()函数。 就像是:

<?php wp_list_comments(); ?>

那么在这种情况下,使用默认的WordPress wp_list_comments函数。 在这种情况下,您需要将自定义回调函数作为参数添加到wp_list_comments()函数中。 那么你需要在functions.php文件中定义这个回调函数。 如果您需要帮助,请随时问。 我将向您展示如何通过向本博客捐款。 您的捐款有助于保持新的代码段即将到来。

3、如果你的主题没有上面两种情况。请参考下面的例子来设置

<?php
function mytheme_comment($comment, $args, $depth) {
$GLOBALS['comment'] = $comment; ?>
<li <?php comment_class('clearfix'); ?> id="li-comment-<?php comment_ID() ?>">
<?php echo get_avatar($comment,$size='38'); ?>
<div id="comment-<?php comment_ID(); ?>">
<div class="comment-meta commentmetadata">
<?php printf(__('<strong>%s</strong>'), get_comment_author_link()) ?>
<?php edit_comment_link(__('(Edit)'),'  ','') ?> <span><?php printf(__('%1$s at %2$s'), get_comment_date(),  get_comment_time()) ?>
<?php bac_comment_count_per_user(); //Display the total Comment count per Author ?>
</span>
</div>

<div class="text">
<?php comment_text() ?>
</div>

<?php if ($comment->comment_approved == '0') : ?>
<em><?php _e('Your comment is awaiting moderation.') ?></em>

<?php endif; ?>

<div class="reply">
<?php comment_reply_link(
array_merge( $args, array(
'depth' => $depth,
'max_depth' => $args['max_depth']
)
)
) ?>
</div>
</div>
<?php }
?>

完成。如果你想自定义你的css,请自行修改。

发表回复