1

Is it possible to show all tags that are related to a category? I can't find anything on it.

Thanks.

Edit:

What I am looking for is this:

I know a category slug or name. I want to get all tags associated with entries in that category.

I can't seem to get this to work using the relatedTo param.

  • Is your tag custom field inside the category or an entry? – Matt P May 28 '16 at 9:28
4

You can use the relatedTo param on craft.tags like you can with any Element inside Craft.

All Elements inside Craft can be related to one another. There is a .relatedTo parameter available on all of the query elements like craft.entries and craft.tags.

You will need to pass a category object into this relatedTo parameter. I have included the group param below but this can be omitted if you want to query all of your tags.

{% set tags = craft.tags.group( 'groupName' ).relatedTo( category ) %}

More info on using Relations in Craft: https://craftcms.com/docs/relations


UPDATE

The relatedTo param takes one of the following:

  • An AssetFileModel, CategoryModel, EntryModel, UserModel, or TagModel object
  • An element’s ID
  • An array of element objects and/or IDs

To get a CategoryModel using a slug inside your template you can use:

{% set category = craft.categories.slug( 'theslug' ).first() %}

This will set category to a CategoryModel which you can then use inside the .relatedTo param in the above example.


UPDATE 2

If you've set category to have their own URL's then category inside the template you've set to use is a CategoryModel.

You then set entries to all entries related to the category. Finally, use these entries to get all related tags.

{% set entries = craft.entries.relatedTo( category ).find() %}
{% set tags = craft.tags.relatedTo( entries ).find() %}
  • Thanks. How do I set the actual category? – Erik May 31 '16 at 12:18
  • That depends on where you are setting these tags to be displayed. You can get categories the same way you get entries using craft.categories. If you have set categories to have their own URLs then category will be the current category you're viewing. – Luke Pearce May 31 '16 at 12:37
  • Ok, thanks for the help! I just started using Craft, so I'm still trying to wrap my ahead around some of the concepts. – Erik May 31 '16 at 12:57
  • Ok, I updated my original question with an edit. I'm still not getting this to work, and maybe I was misunderstood. – Erik May 31 '16 at 17:15
  • So I tried to do that and nothing displayed. I used {% set category = craft.categories.slug('slug') %} and {% set tags = craft.tags.relatedTo( category ) %}. I guess I will just mess around with it a bit more. – Erik May 31 '16 at 17:46

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.