Drupal 7 – Get the number of comments by user

Yesterday we talked about counting the number of nodes by user.
Drupal 7 – Get the number of nodes by user

We could also use similar approach for counting the number of comments by user.

1. Add the following function in your theme template.php

function <theme>_get_user_comments_count($uid) {
  $query = db_select('comment', 'c');
  $query->condition('uid', $uid, '=');
  $query->condition('status', '1', '=');
  $query->addExpression('COUNT(1)', 'count');
  $result = $query->execute();

  if ($record = $result->fetchAssoc())
    return $record['count'];
  
  return 0;
}

 

2. So you could retrieve the comment count by calling

<theme>_get_user_comments_count($uid)

 

3. Here is another version of <theme>_get_user_comments_count($uid) which only counts the comments of specific content type.

function <theme>_get_user_comments_count($uid) {
  $query = db_select('comment', 'c');
  $query->join('node', 'n', 'c.nid = n.nid');
  $query->condition('c.uid', $uid, '=');
  $query->condition('n.type', '&lt;content-type&gt;', '=');
  $query->condition('n.status', '1', '=');
  $query->condition('c.status', '1', '=');
  $query->addExpression('COUNT(1)', 'count');
  $result = $query->execute();

  if ($record = $result->fetchAssoc())
    return $record['count'];
  
  return 0;
}

 

Done =)

Reference: Drupal Forum – Post count (x)/comment count (x) on user profile page

Advertisement

One thought on “Drupal 7 – Get the number of comments by user”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.