Improved Recent Comments List Code Snippet for WordPress

26 Mar 2011

Adding a recent comments list in your WordPress blog is a great technique as it can capture the user’s attention and at the same time help to fill up that empty space in your sidebar.

Quite a number of websites you might know (to name a few,,,, display a recent comments list in their sidebar.

Web Designer Wall’s Recent Comments List

I found a few websites that provide the code snippet for displaying a recent comments list but most of them are duplicates of each other and the comments list isn’t laid out nicely and doesn’t include the comment author avatars.

So here’s an improved version of the popular code snippet for displaying recent comments.
The original code is taken from WP Hacks –

Recent Comments List Code Snippet

This enhanced comments list displays 2 more additional information as compared to the previous version – the author avatar and post title. The Latest Comments tab in my sidebar is using these exact same codes below.

Insert this piece of code in your sidebar:

global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,comment_post_ID, 
comment_author_email, comment_author, comment_date_gmt, comment_approved, 
comment_type, comment_author_url, SUBSTRING(comment_content,1,30) AS 
com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON 
($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved 
= '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt 
$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {
$output .= get_avatar($comment->comment_author_email, 50);
$output .= "\n<li>".strip_tags($comment->comment_author)
." said: " . "<a href=\"" . get_permalink($comment->ID) .
"#comment-" . $comment->comment_ID . "\" title=\"on " .
$comment->post_title . "\">" . strip_tags($comment->com_excerpt)
."</a> in <br/>";
$output .= "<a href=\"" . get_permalink($comment->ID) ."#comment-" . $comment->
comment_ID . "\" title=\"on " .$comment->post_title . "\">".$comment->post_title."
$output .= "\n</ul>";
$output .= $post_HTML;
echo $output;

I hope this code snippet helps you, good luck!

Author - Azhar Kamar
3 Comments Revolving around this Article
  1. yash says:

    how to to display 2 comment

    i want to limit comment count

  2. love says:

    All human progress is usually preceded by innovative questions

  3. türk says:

    thank you nice sharing has been

Write a Comment! NOW! :)

Current ye@r *