4

How can I show Comment Count in a specific place of the node template?
I want to show Comment Count's of a node (article) in the submitted area instead of in the node links area.
I do this already in Drupal 7 with this codes in node.tpl.php:

<?php if (module_exists('comment') && $node->comment) { print t('Comments'). ': ' .$node->comment_count;} ?>

or this code:

<a href="<?php print $node_url;?>#comments"><?php print t('Comments'). ': '. $comment_count; ?></a>

What is the equivalent code for Drupal 8?

2
  • @kiamlaluno: Please reopen this post, This question is about Drupal 8 but that's about Drupal 7, node.tpl Dec 3, 2016 at 14:35
  • No, that question is not for Drupal 7. It doesn't have any version tag, and there is an answer for Drupal 8.
    – apaderno
    Dec 3, 2016 at 15:25

1 Answer 1

8

Use this code in your theme's YOUR_THEME.theme file:

function YOUR_THEME_preprocess_node(&$variables) {
  // Note: you'll probably want this only for certain content types.
  if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $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 }}
5
  • Thank you for your efforts, but i don't know where is the problem that howsoever I trying to get a result, i can't become success. Could you explain more about this code, How should I use this code in my theme? Mar 14, 2016 at 15:00
  • I mentioned where each piece of code should go to; I don't completely understand your question. The first part (hook_preprocess_node()) goes into YOUR_THEME.theme file. The other part is how you use that in your node templates. If this is not what you meant, please explain. Mar 14, 2016 at 18:54
  • 2
    Those are machine names for your content type and your comment field. Machine name is displayed under the label. For example, when you are adding "Article" content type, your machine name will be "article"; if you create "Article Comments" field, machine name will be "field_article_comments". Mar 15, 2016 at 8:26
  • 1
    Content type machine name, and field machine name. Mar 19, 2016 at 17:57
  • You're welcome - glad it helped :) Mar 20, 2016 at 17:29

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