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