Display user’s total comment count outside The Loop

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.

Leave a Comment