Skip to content

How To Display Recent Comments In WordPress

Comments are a way for people to discuss things and tell you what they thing about your work. It’s a good idea for you to display recent comments in WordPress to appreciate all the feedback you get from your readers. It also increase the chances of a reader commenting on your website.

WordPress has an official widget for this job, but that widget will show the names of the post, not the comment itself on the sidebar. There are also tons of plugins to display recent comments of your WordPress in the front-end of your website, but why waste your time with plugins when you can do it without a plugin?

Courtesy of WPLancer, here’s a code which will do the job. First, add following code to your current theme’s functions.php file or a site-specific plugin:

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.';

    echo $comm; 

You can define number of comments, gravatar size and comment length in the first line.

Now, add following code anywhere in your WordPress theme where you want to display the recent comments:

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

You can also add some CSS to style the widget if you want to:

.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; }

Leave a Reply

Your email address will not be published. Required fields are marked *