1

I have the following categories

  1. Tech (1 entry: case A) 1.1 Apps 1.2 Software (2 entries: case B)
  2. Fashion 2.1 Clothing (1 entry: case C) 2.2 Shoes ...

When using {{ entry.categories.one().url }}, it always show the parent category (Tech, Fashion). In case A, the category is Tech. In case B and C, I want to show the child categories. Here are the expected category URL of an entry:

  1. example.com/tech
  2. example.com/software
  3. example.com/clothing

Do you have any simple way to display the final category? The final category is a parent or child one. Thanks for your answer!

1 Answer 1

1

This is a common gotcha with categories, as the mechanism for relating to them is different from entries. When you relate an element to an entry, only that entry gets related. But when you relate an element to a category, each of that category's parent categories becomes related to the element as well. This explains why categories.one() returns the top parent category, because that parent is the first one related in the field.

If your categories field is limited to a single branch, a trick is to simply reverse the categories query, i.e. to return the last (lowest) category selected in the field:

{{ entry.categories.inReverse().one().url }}

Note that this only works reliably when there is only a single branch selected in the categories field. If there are multiple branches, you'll probably be better off using entries (i.e. a structure section) for your "categories" instead of actual categories.

1
  • 1
    Many thanks! Your answer is very useful and I'll try it. Dec 12, 2022 at 8:23

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.