Search code examples
phpwordpresscountcomments

Show user's total comment count outside The Loop in Wordpress


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

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

    <?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 fine 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?


Solution

  • Try making a few things more global and getting the user data differently.

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

    or in functions.php

    <?
    function commentCount() {
        global $wpdb, $current_user;
        get_currentuserinfo();
        $userId = $current_user->ID;
    
        $count = $wpdb->get_var('
                 SELECT COUNT(comment_ID) 
                 FROM ' . $wpdb->comments. ' 
                 WHERE user_id = "' . $userId . '"');
        echo $count . ' comments';
    }
    ?>
    

    To call it

      <?php commentCount(); ?>