In previous articles we have shown you how to display most commented blog posts and today we will discuss about displaying recent comments in WordPress.
WordPress comes with a recent comments widget out of the box. Although it’s very handy, but on the other hand does not give you much freedom in terms of customizing look and feel. And also it can only be used in pre-defined widget locations on your website. There are number of plugins available which offer same functionality with more features, but sometimes you just want more control and free yourself from any limitations. So in this article I will show you the easy way to display most recent comments in your website anywhere you want.
This code snippet will output list of five most recent comments and their links. You can change the number of recent comments displayed by changing the number 5 in following code snippet. Just so you know, this snippet will only return recent comments with approved status. Although you can change comment status to display unapproved too, but I am not sure why would you want to do that on your website.
All you need to do is to simply paste this WordPress code snippet in your theme file where you want to display this list, preferably in sidebar.
<?php
// display most recent comments in wordpress
$args = array (
'status' => 'approve',
'number' => '5'
);
$comments = get_comments( $args );
if ( !empty( $comments ) ) :
echo '<ul>';
foreach( $comments as $comment ) :
echo '<li><a href="' . get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID . '">' . $comment->comment_author . ' on ' . get_the_title( $comment->comment_post_ID ) . '</a></li>';
endforeach;
echo '</ul>';
endif;
?>