Display user’s total comment count outside The Loop

How do I display a user’s total comment count outside The Loop?

I use this code to display comment count inside the loop:

Read More
    <?php
    global $wpdb;
    $user_id = $post->post_author;
    $where = 'WHERE comment_approved = 1 AND user_id = ' . $user_id ;
    $comment_count = $wpdb->get_var(
        "SELECT COUNT( * ) AS total
    FROM {$wpdb->comments}
    {$where}
");
    echo 'Comments: <strong>' . $comment_count . '</strong>';
    ?>

That works perfectly inside the loop. In an attempt to make that code work outside the loop, I changed $user_id = $post->post_author; to $user_id = get_the_author_meta( 'ID' ); but it did not work.

The closest that I have been is with this code:

                            <?php
                            global $wpdb;
                            $where = 'WHERE comment_approved = 1 AND user_id <> 0';
                            $comment_counts = (array) $wpdb->get_results("
                                SELECT user_id, COUNT( * ) AS total
                                FROM {$wpdb->comments}
                                {$where}
                                GROUP BY user_id
                                ", object);
                            foreach ( $comment_counts as $count ) {
                                $user = get_userdata($count->user_id);
                                echo 'Comments: ' . $count->total . '
                                ';
                            }
                            ?>

However, this echos comment count for all users, like this: “Comments: 28 Comments: 11 Comments: 55” etc

What code can I use to show the user’s comment count outside the loop?

Related posts

Leave a Reply

1 comment

  1. You are more or less there already with the code, you just need to change the code slightly.

    You do not mention how you get the user id, but if you have the user ID you want to check, it is quite easy to do outside the loop.

    Here is a simple example:

    $userid=1;
    $comment_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) AS total FROM $wpdb->comments WHERE comment_approved = 1 AND user_id = %s", $userid ) );
    echo "Number of comments for user $userid is $comment_count";
    

    Note: the part of the query that says “comment_approved = 1” counts only the approved comments, if you want to include the non-approved comments leave out that part.