1

How do you set a variable to a specific category so you can do an if or for loop? I have entries(staffList) associated to categories (Management,Staff,Other,PartTime)and I am trying to set a variable to do a loop off of and pull the entry fields but am having a difficult time setting the variable to pull just a specific category.

Below is what I am using to set:

{% set staff = craft.entries.section('staffList').relatedTo('Management') %}

Any ideas where I am going wrong?

2

You can't just pass a string (category name) to relatedTo, you need to pass either the category ID or a complete CategoryModel (you can also pass in an array of IDs or models, if there are several categories).

This means that unless you already have the category IDs or models, you'll need to pull them using the craft.categories service:

{% set management = craft.categories.title('Management').first() %}

{% set staff = craft.entries.section('staffList').relatedTo(management) %}

If you have multiple category groups, and there's a possibility you might have multiple categories across those groups with the same name, you should specify which category group the category you're after belongs to:

{% set management = craft.categories.group('categoryGroupHandle').title('Management').first() %}

If you want to pull staff entries related to multiple categories, here's how that could look:

{% set categories = craft.categories.title(['Management', 'Staff', 'Other']) %}

{% set staff = craft.entries.section('staffList').relatedTo(categories) %}

Finally, keep in mind that if you're rendering a category template (i.e. you've requested the URL for a particular category and Craft has rendered the template specified in the relevant category group's template path), Craft will actually populate the template with a category variable, containing the CategoryModel for the category belonging to that URL. If this is the case, then you simply need to do this:

{% set staff = craft.entries.section('staffList').relatedTo(category) %}

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.