1

Okay, all I want to do is list all categories AND the # of entries associated with each category.

{% set numofEntries = craft.entries.section('posts').relatedTo(category).total() %}

<p class="tags">
    {% for categoryName in craft.categories.group('markets') %}
        <a href="{{ categoryName.url }}">{{ categoryName.title }}-{{numofEntries}}</a>
    {% endfor %}
</p> 

No error is thrown (and I am in dev mode), but the number that appears (49) is the same for all categories (and doesn't even equal the number of total entries).

A few things...

  • market group = markets ...

  • the category field handler = marketName

2

You'll want to query for the number of entries inside the for loop.

{% for categoryName in craft.categories.group('markets') %}
    {% set numofEntries = craft.entries.section('posts').relatedTo(categoryName).total() %}

    <a href="{{ categoryName.url }}">{{ categoryName.title }}-{{numofEntries}}</a>
{% endfor %}

2

If you want to display the total number of entries related to each category, you'll need to put the {% set numofEntries ... %} statement inside your for loop. You'll also need to change the relatedTo(category) part to relatedTo(categoryName) (or change the categoryName to category, which would probably be more appropriate).

Something like this should work:

{% set numofEntries = craft.entries.section('posts').relatedTo(category).total() %}

<p class="tags">
    {% set categories = craft.categories.group('markets') %}
    {% for category in categories %}
        {% set numofEntries = craft.entries.section('posts').limit(null).relatedTo({
            targetElement: category,
            field: marketName
        }).total() %}
        <a href="{{ category.url }}">{{ category.title }}-{{numofEntries}}</a>
    {% endfor %}
</p> 

Note: You don't actually need to feed the targetElement and field attributes to the relatedTo() parameter – simply relatedTo(category) will usually work just fine – but it's supposedly more performant to be as specific as possible about the relation you're looking for – in this case; any entries that have the category selected (i.e. the targetElement) in the Categories field marketName.

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.