To display recent comments on the sidebar doesn’t necessarily require us to use a plugin or widget. We can achieve the similar result by just adding lines of PHP codes into it.
<?php $comments = get_comments('status=approve&number=5'); if ($comments) { echo '<ul id="recent_comments">'; foreach ($comments as $comment) { echo '<li><a href="'. get_permalink($comment->comment_post_ID).'#comment-'.$comment->comment_ID .'" title="'.$comment->comment_author .' | '.get_the_title($comment->comment_post_ID).'">'; echo '<span class="recent_comment_name">' . $comment->comment_author . ': </span>'; $comment_string = $comment->comment_content; $comment_excerpt = substr($comment_string,0,100); echo $comment_excerpt; if (strlen($comment_excerpt) > 99){ echo ' ...'; } echo '</a></li>'; } echo '</ul>'; } else{ echo '<ul id="recent_comments"> <li>No comments yet</li> </ul>'; } ?>
In order to get the Gravatars to be displayed, the following codes must be added to your theme’s function.php. But if you already have this piece of code you may skip this part.
<?php add_filter( 'avatar_defaults', 'newgravatar' ); function newgravatar ($avatar_defaults) { $myavatar = get_bloginfo('template_directory') . '/images/YOUR_IMAGE_HERE.png'; $avatar_defaults[$myavatar] = "Custom Gravatar"; return $avatar_defaults; } ?>
To change the number of comments to be displayed, edit the number at the end of this line:
$comments = get_comments('status=approve&number=5');
If you want to the commenters’ Gravatars to be displayed before each comment, look for the following codes:
echo '<li><a href="'. get_permalink($comment->comment_post_ID).'#comment-'.$comment->comment_ID .'" title="'.$comment->comment_author .' | '.get_the_title($comment->comment_post_ID).'">' ;
And add this line just before the last ;
. get_avatar( $comment->comment_author_email, $img_w)
By default the comment excerpts would be displayed 100 characters long. To change the length, look for this line:
$comment_excerpt = substr($comment_string,0,100);
and this line:
if (strlen($comment_excerpt) > 99){
Change 100 to any number you want and change 99 to a number that is one value smaller than the first number. For example, if you want the excerpt to be 50 characters long, the second number should be 49.