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?
Try making a few things more global and getting the user data differently.
or in functions.php
To call it
I know this topic is old but just want to drop a snippet, which is far more suitable :
Where ‘post_id’ can be ‘user_id’
You should use
WHERE comment_author_email = "' . get_comment_author_email() . '"
to get the comment per user if you are watching their profile… The code of @SMacFadyen will give the logged in users comment count only.Besides, the second function does not work.
Try this one
As a function, passing the $user_id – also uses $wpdb->prepare() method to format the query: