WP 优化

WordPress 最近评论

2年前 (2021-10-20)   1.26k   1277 字

我们知道 WordPress 官方小工具中自带的就有近期评论,但是 WordPress 自带的近期评论是显示的文章标题,而非人们留下的评论本身,当然,也有许多这样的插件,但是插件多了毕竟不是一件好事,会影响网站的速度不是吗?所以,如果能不用插件,还是尽量的不用插件,将下面的代码添加到您的当前主题的 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 头像尺寸等等。
然后,添加下面的代码到您想要显示的位置

<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; }
版权声明:Jakehu 发表于 2021-10-20 18:49:11
转载请注明:WordPress 最近评论︱Jakehu

您可能感兴趣的

暂无评论

暂无评论...