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?

15

You can access the categories through the category field itself.

{% for category in entry.categoryFieldHandle %}
    {{ category.title }}
{% endfor %}
  • 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 Jan 26 '15 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. – Douglas McDonald Jan 26 '15 at 20:22
5

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.

  • When trying this, I get no output, even when the entry has multiple categories set :-/ – taylor Jan 26 '15 at 19:58
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, privacy policy and cookie policy

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