0

I have an entry page that lists out specific info for a product. I am using categories to sort the entries. I'm trying to figure out how to write a conditional that pulls in something specific if the entry belongs to a specific category.

2
  • So, you have a categories-field on the entry, and if a specific category is selected, you want to do something? Commented Nov 14, 2016 at 16:51
  • ya, in the entry you can select the category it's in and so I want to display something for entries that belong to a certain category. Commented Nov 14, 2016 at 16:55

1 Answer 1

3

The category field returns an ElementCriteriaModel, which means you can use all the methods that you'd usually use to get a specific category on it.

For instance, if the category field is named entryCategories, and you know the slug of the category you want to test for, you could do:

{% if entry.entryCategories.slug('my-category-slug').total() %}
    Do something
{% endif %}

Or you could use the idthe same way.

Please note, this does not work if the entryCategory field was eager-loaded, since entry.entryCategories would then return an array. In that case you could just loop over the array and have a check inside for loop that checks the category you're looping over is the correct one. A bit dirty, but it does the job.

1
  • 1
    @MatthewCarleton I just updated the answer to exchange the length filter for the more efficient total() method. Instead of querying the category models it just queries for the count of rows in the database. The query itself is quicker and it also uses much less memory.
    – carlcs
    Commented Nov 14, 2016 at 17:59

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.