Add comment counter to posts

Drupal

If you want to add a comment counter to posts (to display the number of comments) you could add that to the node template by using $node->comment_count but this sort of thing tends to get ugly. It's neater to add the counter to the node links.

I added the following snippet to template.tpl.php:

<?php

/**
 *
 * Preprocess function for node
 *
 */
function phptemplate_preprocess_node(&$vars) {

 
// --- Add comment counter in forum nodes ---
  // Only for these node types
 
$node_types = array('forum');
  if (
user_access('access comments') && in_array($vars['node']->type, $node_types)) {
   
// Obtain current links
   
$links = $vars['node']->links;
   
// Add list element
   
$links['comment_comments' ] = array(
     
'title' => format_plural($vars['node']->comment_count, t('1 comment'), t('@count comments')),
     
'attributes' => array('title' => t('Number of comments on this post'))
    );
   
// Write new links
   
$vars['links'] = theme('links', $links, array('class' => 'links inline'));
  }


}

?>

By using the same class comment_comments for the counter as used by Drupal in the teaser preview nothing needs to be added to the CSS style sheets.

You could add the clause $vars['node']->comment_count > 0 to omit the counter when there are no comments yet.

You may also want to check for !$vars['is_front'] so the counter is omitted when on the front page (Drupal adds its own and links it to the comments).

<?php
if ($vars['node']->comment_count > 0 && !$vars['is_front'] && in_array($vars['node']->type, $link_types)) {
}
?>