I'm trying to create a small list of top commenters in my sidebar. I don't want to use a plugin, so I was googling for codes. All I could find was the following:

function top_comment_authors($amount = 5){

    global $wpdb;

    $results = $wpdb->get_results('
            COUNT(comment_author_email) AS comments_count, comment_author_email, comment_author, comment_author_url
            comment_author_email != "" AND comment_type = "" AND comment_approved = 1
        GROUP BY
        ORDER BY
            comments_count DESC, comment_author ASC
        LIMIT '.$amount


    $output = "<ul>";
    foreach($results as $result){
        $output .= "<li>".$result->comment_author."</li>";
    $output .= "</ul>";

    echo $output;


I already modified it because I also want the post count and author url to show up. I also want to add a gravatar later on. However, it just displays everything next to each other:

enter image description here

$output .= "<li>".$result->comment_author. $result->comments_count. $result->comment_author_url."</li>";
    $output .= "</ul>";

    echo $output;


Whenever I try to add something, I end up getting an error message. I'm pretty sure I need to modify the little code above if I want to change the way it's displayed, but HOW?! :/

This is how I call the function, so no room for customization other than in the function.php, right?:

<?php top_comment_authors(); ?>

I'm not really good with PHP, so I wonder how I'd do something like this:

[gravatar] "commenters-name-as-url-if-available" (comment-count) e.g. "japanworm (45)"

If anybody could help me a little, that would be great. Thanks a lot!

1 Answer 1

$output .= "<li>".(($result->comment_author_url) ? "<a href='".$result->comment_author_url."'>" : "").$result->comment_author.(($result->comment_author_url) ? "</a>" : "")." (".$result->comments_count.")</li>";

edit: to show the avatar before the name:

$output .= "<li>".get_avatar($result->comment_author_email, 45).' '.(($result->comment_author_url) ? "<a href='".$result->comment_author_url."'>" : "").$result->comment_author.(($result->comment_author_url) ? "</a>" : "")." (".$result->comments_count.")</li>"; 
  • Hello. Thank you so much. This works well! However, I also want a gravatar to be shown. I tried the following code, but it doesn't work: <ul> <li> <?php foreach ($comments as $comment) { ?> <?php echo get_avatar( $comment, '45' ); ?> <?php } ?> <?php top_comment_authors(); ?></li> </ul>
    – japanworm
    Commented Sep 26, 2011 at 4:34
  • 1
    I have expanded my answer with a possible code to show the avatar before the name.
    – Michael
    Commented Sep 26, 2011 at 8:05
  • Awesome, thank you so much!! Works perfectly fine! :)
    – japanworm
    Commented Sep 26, 2011 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.