WordPress获取文章评论人数并输出评论用户列表
通过WordPress我们可以轻松获取文章总的评论数,同时在文章中通过列表展示出来,最近在制作评论模板的时候我就在想,能不能通过一Tab效果,正常显示评论列表,通过Tab切换显示评论者列表呢?答案是肯定的,并且已经有人实现了。
第一步:我们需要获取文章总的评论人数:
/* 获取文章的评论人数*/
function tuts_comments_users($postid=0,$which=0) {
$comments = get_comments('status=approve&type=comment&post_id='.$postid); //获取文章的所有评论
if ($comments) {
$i=0; $j=0; $commentusers=array();
foreach ($comments as $comment) {
++$i;
if ($i==1) { $commentusers[] = $comment->comment_author_email; ++$j; }
if ( !in_array($comment->comment_author_email, $commentusers) ) {
$commentusers[] = $comment->comment_author_email;
++$j;
}
}
$output = array($j,$i);
$which = ($which == 0) ? 0 : 1;
return $output[$which]; //返回评论人数
}
return 0; //没有评论返回0
}
第二步:输出总的评论用户列表:
/*输出文章评论头像列表*/
function tuts_comments_user_avatars($postid=0) {
$comments = get_comments('status=approve&type=comment&post_id='.$postid); //获取文章的所有评论
if ($comments) {
$commentusers=array();
$commentusers=array();
foreach ($comments as $comment) {
if ( !in_array($comment->comment_author_email, $commentusers) ) {
echo '<li class="uk-text-center uk-text-meta">';
echo '<img src="https://secure.gravatar.com/avatar.php?gravatar_id='.md5($comment->comment_author_email).'" alt="'.$comment->comment_author.'">';
echo "<a href='".$comment->comment_author_url."' target='_blank' rel='nofollow' ";
echo 'title="'.$comment->comment_author.'"';
echo " class='tuts_tooltip uk-text-truncate tuts_avatar_names'>".$comment->comment_author."</a>";
echo '</li>';
$commentusers[] = $comment->comment_author_email;
}
}
}
}
第三步:在需要的地方调用:
<ul class="uk-list uk-padding-small tuts_comments_user_avatars"> <?php tuts_comments_user_avatars(get_the_ID()); ?> </ul>