Is your blog popular? Do you got receive lots of comments from your readers? If yes, what about displaying the most recent comments in your blog sidebar (or elsewhere) to let your visitors knowing about the discussion?
Is your blog popular? Do you got receive lots of comments from your readers? If yes, what about displaying the most recent comments in your blog sidebar (or elsewhere) to let your visitors knowing about the discussion?
In order to display the 5 most recent comments with their gravatars, paste this code anywhere on your theme files. To get more or less than 5 comments, change the number 5 on line 2.
<?php
$query = "SELECT * from $wpdb->comments WHERE comment_approved= '1'
ORDER BY comment_date DESC LIMIT 0 ,5";
$comments = $wpdb->get_results($query);
if ($comments) {
echo '<ul>';
foreach ($comments as $comment) {
$url = '<a href="'. get_permalink($comment->comment_post_ID).'#comment-'.$comment->comment_ID .'" title="'.$comment->comment_author .' | '.get_the_title($comment->comment_post_ID).'">';
echo '<li>';
echo '<div class="img">';
echo $url;
echo get_avatar( $comment->comment_author_email, $img_w);
echo '</a></div>';
echo '<div class="txt">Par: ';
echo $url;
echo $comment->comment_author;
echo '</a></div>';
echo '</li>';
}
echo '</ul>';
}
?>
16 Responses
what a great code snipet, lol
My only comment is that you’ve used SELECT * which is pretty inefficient if you’re a large blog. Any reason you went that route instead of pointing out just the fields you need?
I don’t like the SQL Query. You could do it like this instead, before the loop:
$comments = get_comments(‘status=approve&number=5′);
What does ‘$img_w’ represent?
aah.. nice snippet indeed
@Chris..
SELECT * only select the columns, it doesn’t matter if your a small or large blog as your rows are limited to 5..
@Jens
that must be something new then or template specific, as the tag “get_comments” is nowhere mentioned in the WordPress Codex
@JP : It is the user defined size for the gravatar.
@IsSidha
Yes, it might be new but it works. I’m using it on my blog jenst.se, in the sidebar.
get_comments is in the codex:
http://codex.wordpress.org/Function_Reference/get_comments
Hi! How do you limit the comments to excerpts?
wow, i found it… and it works
Thanx JBJ, i will use it on my blog in the sidebar
Great piece of code. Thanks for sharing. I agree with Chris and Jens on not using an SQL query. The less we hit the database, the more efficient our code is going to be
@aopinionlatina: you can show comment’s excerpt in the following manner -
$excerpt = wp_html_excerpt( $comment->comment_content, 30 );
Great! I was looking for this code. Thanks!
It would be nice if you put a screen shot up of exactly what this would look like. i appreciate the code tho. I have a plugin installed and It made my sidebar comments look terrible
Trackbacks: