6

For templating, I need to be able to see what the categories of the current entry is. I'm aware of how to get all categories in craft via

{% set categories = craft.categories %}

however I haven't come across a way to simple get the categories that are set for the entry. Is there a simple way of doing this?

3 Answers 3

16

You can access the categories through the category field itself.

{% for category in entry.categoryFieldHandle %}
    {{ category.title }}
{% endfor %}
2
  • When trying this in _entry.html, I get an internal server error "Craft\EntryModel and its behaviors do not have a method or closure named "categoryFieldHandle"."
    – taylor
    Commented Jan 26, 2015 at 19:57
  • 1
    'categoryFieldHandle' is just a placeholder for your category field name (technically called it's 'handle'). You should replace this with your field handle as defined in the field settings. Commented Jan 26, 2015 at 20:22
6

If might be your wording but I can see two potential answers here.

You either want to list categories set through a category field on the entry, in that case the code Douglas has supplied will work perfectly.

The other answer I can see is you have multiple categories that are assigned to an entry, and you want to list those categories out. If so, this will help:

{# Fetch all of the categories related to this entry #}
{% set categories = craft.categories.relatedTo(entry) %}

{# Output them #}
{% for category in categories %}
    <a href="{{ category.url }}">{{ category.title }}</a>
{% endfor %}

Hopefully myself and Douglas have covered both bases for you here.

2
  • 1
    When trying this, I get no output, even when the entry has multiple categories set :-/
    – taylor
    Commented Jan 26, 2015 at 19:58
  • 1
    Just for anyone seeing this 7 years later: craft.categories().relatedTo(entry).all() or collect() etc etc
    – Rob Hodges
    Commented Jun 2, 2022 at 23:04
1

Your entry is tied to the category via the field you have made. You can access the field like every other field.

entry.categoryFieldName.one()

Will get the first one

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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