With
{% for category in entry.categories.all() %}
<a href="{{ category.url }}">{{ category.title }}</a> {{ not loop.last ? '| ' }}
{% endfor %}
How do I exclude a specific category from displaying?
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityI might be mistaken, but you can just insert an if
block into your loop:
{% set excludedId = 1234 %}
{% for category in entry.categories.all() %}
{% if category.id != excludedId %}
<a href="{{ category.url }}">{{ category.title }}</a>
{{ not loop.last ? '|' }}
{% endif %}
{% endfor %}
That said, this will no longer know whether the "last" item in the loop was excluded. A better solution might be to trim down the collection before beginning the iteration:
{% set excludedId = 1234 %}
{% for category in entry.categories.all() | filter((c) => c.id != excludedId) %}
<a href="{{ category.url }}">{{ category.title }}</a>
{{ not loop.last ? '|' }}
{% endfor %}
This makes use of the filter
filter, which you can pass a "function" of sorts to compare each ID to your excluded one. If the comparison is false
, it'll remove it from the collection before the loop starts.
One last option (and possibly the best one) is to adjust the query itself, before it's run:
{% set excludedId = 1234 %}
{% set onlyDesiredCategories = entry.categories.id("not #{excludedId}").all() %}
{% for category in onlyDesiredCategories %}
<a href="{{ category.url }}">{{ category.title }}</a>
{{ not loop.last ? '|' }}
{% endfor %}
Instead of filtering down from the natural relations, this method attempts to adjust the ElementQuery
instance provided by the relation field (entry.categories
) by setting the id
param to not 1234
, meaning that ID will be excluded when the query is executed. I haven't actually tried this lat method, myself, so your mileage may vary.