WordPress教程:如何在WordPress中显示近期评论

评论是可以让人们讨论关于生活工作等的事情,在WordPress上显示近期评论是一个非常不错的主意,你能从读者哪里掌握更多关于文章的反馈,读者也能将他们精彩的评论展现在你的WordPress网站上,两全其美的事情,何乐而不为?
我们知道WordPress官方小工具中自带的就有近期评论,但是WordPress自带的近期评论是显示的文章标题,而非人们留下的评论本事,当然,也有许多这样的插件,但是插件多了毕竟不是一件好事,会影响网站的速度不是吗?所以,如果能不用插件,俺们还是尽量的不用插件,具体可以参考:http://www.wpmee.com/no_category_base/ 中引用的语句。
首先,将下面的代码添加到您的当前主题的functions.php文件中:

function bg_recent_comments($no_comments = 5, $comment_len = 80, $avatar_size = 48) {
  $comments_query = new WP_Comment_Query();
    $comments = $comments_query->query( array( "number" => $no_comments ) );
    $comm = "";
    if ( $comments ) : foreach ( $comments as $comment ) :
        $comm .= "<li>" . get_avatar( $comment->comment_author_email, $avatar_size );
        $comm .= "<a class="author" href="" . get_permalink( $comment->post_ID ) . "#comment-" . $comment->comment_ID . "">";
        $comm .= get_comment_author( $comment->comment_ID ) . ":</a> ";
        $comm .= "<p>" . strip_tags( substr( apply_filters( "get_comment_text", $comment->comment_content ), 0, $comment_len ) ) . "</p></li>";
    endforeach; else :
        $comm .= "No comments.";
    endif;
    echo $comm;
}  

您可以在第一行设置适合你的评论条数,最长评论字数限制,以及gravatar头像尺寸长度等等。
然后,添加下面的代码到您想要显示最近的评论在您的WordPress主题的任何位置(如何在文本小工具运行PHP,比如下面的代码,请参考:http://www.wpmee.com/use-php-wordpress-widgets/):

<div class="widget recent-comments">
<h3>Recent Comments</h3>
<?php bg_recent_comments(); ?>
</div>  

最后你也可以添加下面的CSS到你的style.css文件中:

.recent-comments { list-style: none; font-size: 12px; color: #485358; }
.recent-comments li { overflow: hidden; padding: 20px 0; border-top: 1px dotted #DADEE1; }
.recent-comments li:first-child { border: 0 none; }
.recent-comments img { float: left; margin-right: 8px; }
.recent-comments a { display: block; margin-top: 10px; padding-top: 10px; }