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', '<content-type>', '='); $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
One thought on “Drupal 7 – Get the number of comments by user”