1

I would like to count comments that belong to a certain entry (product). I have this so far:

{% set comments = craft.entries().section('productcomments').all() %}
 {% set counter = 0 %}
  {% for comment in comments %}
   {% if comment.title|length and comment.title == entry.title %}
    {% set counter = counter+1 %}               
    {{ counter }} comments
   {% endif %}
  {% endfor %}

This actually works, but it displays the results after each other (like this:1 comment 2 comment 3 comment - if i have 3 comments). I would like to show only "3 comments". Actually display the max result. Twig's "loop.last" doesn't work because of the condition. Is there another way? Thank you very much!

3

Assuming that your products are entries, and comments are related to a product through an entries field, you can use the following:

{% set comments = craft.entries.section('productcomments').relatedTo(entry).all() %}

This uses the relatedTo parameter.

You can then return how many comments are found by using:

{% if comments|length %}
    <p>{{ comments|length }} comments</p>
{% endif %}
| improve this answer | |
  • Thank you. This works. But i always have to choose the comments manually in the product entry through an entries field? It's actually to much work just to show how many entries are made. if i could write the "count" result in an array, then i could use twig's max function. Is that possible? – TomS Feb 16 '19 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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