Drupal - How To Show Node Comment Count in node.tpl?
You can use $comment_count
in node.tpl.php.
$type
: Node type, i.e. story, page, blog, etc.
$comment_count
: Number of comments attached to the node.
I recommend you use template_preprocess_node().
This is a basic example for D8
function YOUR_THEME_preprocess_node(&$variables) {
$variables['comment_count'] = $variables['node']->get('YOUR_COMMENT_FIELD')->comment_count;
}
And then you can use it in your node.html.twig
file like so:
{{ comment_count }}
A basic example in D6 is below, you can customize it to your liking. In your template.php file located in your theme directory, add something along the lines of (replacing YOURTHEME with the name of your theme):
function YOURTHEME_preprocess_node(&$variables) {
$nid = $variables['node']->nid;
$variables['num_comments'] = db_result(db_query('SELECT COUNT(cid) AS count FROM {comments} WHERE nid = %d', $nid)) . ' comment(s) on this node';
}
and save the file. Now in node.tpl.php (or any equivalent template, node-mycontenttype.tpl.php, etc) simply add:
<?php print $num_comments; ?>
Wherever you would like the comment count to be located and save. Clear the cache and then view your changes.
Update, for Drupal 7 your query on template.php should look like:
$vars['num_comments'] = db_query("SELECT COUNT(cid) AS count FROM {comment} WHERE nid =:nid",array(":nid"=>$vars['nid']))->fetchField();