Craft 3 Documentation

Categories Fields

Categories fields allow you to relate categories to the parent element.

Settings #

Categories fields have the following settings:

The Field #

Categories fields list all of the currently selected categories, with a button to select new ones:

Clicking the “Add a category” button will bring up a modal window where you can find and select additional categories:

When you select a nested category, all of the ancestors leading up to that category will also automatically be selected. Likewise, when you deselect a category from within the main field input, any of its descendants will also become deselected.

Templating #

If you have an element with a Categories field in your template, you can access its selected categories using your Category field’s handle:

{% set categories = entry.categoriesFieldHandle %}

That will give you an element query, prepped to output all of the selected categories for the given field. In other words, the line above is really just a shortcut for this:

{% set categories = craft.categories({
    relatedTo: { sourceElement: entry, field: "categoriesFieldHandle" },
    limit:     null
}) %}

(See Relations for more info on the relatedTo param.)

Examples #

To check if your Categories field has any selected tags, you can use the length filter:

{% if entry.categoriesFieldHandle|length %}
    ...
{% endif %}

To loop through the selected categories:

{% nav category in entry.categoriesFieldHandle.all() %}
    ...
{% endnav %}

Rather than typing “entry.categoriesFieldHandle” every time, you can call it once and set it to another variable:

{% set categories = entry.categoriesFieldHandle %}

{% if categories|length %}

    <h3>Some great categories</h3>
    {% nav category in categories %}
        ...
    {% endnav %}

{% endif %}

You can add parameters to the ElementCriteriaModel object as well:

{% set categories = entry.categoriesFieldHandle.orderBy('name') %}

If your Categories field is only meant to have a single category selected, remember that calling your Categories field will still give you the same ElementCriteriaModel, not the selected category. To get the first (and only) tag selected, use one():

{% set category = entry.myCategoriesField.one() %}

{% if category %}
    ...
{% endif %}

See Also #