0

hi i want to show author comment count in author page. this code can display current user comment count but i dont want current user i need any user please help me

/* user commnet count */
    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 'Şərh sayı ' . $count ;
    }
      <?php commentCount(); ?>

1 Answer 1

1

all you have to do is to add an param:

/* user commnet count */
function get_comment_count( $user_ID ) {
    global $wpdb;

    $count = $wpdb->get_var(
        $wpdb->prepare( "SELECT COUNT(comment_ID) FROM {$wpdb->comments} WHERE user_id = %d ", $user_ID )
    );
    return $count;
}
<?php echo get_comment_count( <USER_ID> ); ?>

PS. I've added some proper escaping in your query also, so this code is not vulnerable any more...

But you can also use...

WordPress already has its own way of doing it, so you don't have to reinvent the wheel... You can use:

$count = get_comments( array(
    'user_id' => <USER_ID>, // include only comments by this user
    'count' => true // it will return only count of comments and not the comments
) );
echo $count;
3
  • thank you very much. but is it possible that <USER_ID> get automaticly in author page. because i dont want to insert user id manuallu. thank for attention Commented Feb 19, 2020 at 9:50
  • 2
    Yes. If you're placing this code in author.php (author's archive) you can use get_queried_object_id() to get the ID of author. Commented Feb 19, 2020 at 9:51
  • Thanks so much. it works.. God bless you Commented Feb 19, 2020 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.