2

So, i have a channel called images and a couple of category groups one of which is called "images" which has categories called family, animals, individuals in it.

So, i just want to grab the entries that have one of those categories assigned / related to them.

Figured something like this would do it

    {% for entry in craft.entries.section('images').relatedTo('photography').find('family') %}
        <h3>{{ entry.title }}</h3>
    {% endfor %}

But i figured wrong! Any ideas would be gratefully received!

13

This should do what you are looking for:

{% set category = craft.categories.slug('family') %}
{% set entries = craft.entries.section('images').relatedTo(category).find() %}

{# If there are any entries, loop through them #}
{% if entries | length %}

    {# For each entry we find, do this #}
    {% for entry in entries %}
        <p>{{ entry.title }}</p>
    {% endfor %}

{% endif %}

So we are creating a variable called category, in which you set the category you want to get the list of related entries from.

Next we set a variable called entries, which checks to see if there are any entries in the Image section that relate to the category we set.

It then loops through the entries that we find (if there are any).

EDIT

More than one category group might have the Family category. To get round this you can target a specific category group when we set the category variable:

{% set category = craft.categories.group('categoryGroup').slug('family') %}
  • Hmm, my problem with that is there may be more than category group that has a category of 'family' in it. Is there a way to specify both category group and category? Thanks btw!!! – John Oct 14 '14 at 15:11
  • Sure, no problem, I have edited my answer. Just swap out categoryGroup with the category group you want to target. – Jamie Wade Oct 14 '14 at 15:17
  • You're welcome! – Jamie Wade Oct 14 '14 at 16:24
  • 1
    This makes much more sense now. I think the docs could make it a little more explicit in it's examples that you're passing an object as parameters, especially for those of us new to programming (I'm sure there are going to be lots of us as Craft grows!) – Rob Jan 7 '16 at 23:37
  • 1
    For those coming here via search and using Craft 3, make sure you add .one() when retrieving the category, e.g. {% set category = craft.categories.group('categoryGroup').slug('family').one() %}, otherwise you won't get any entries matching. – natebeaty May 7 '18 at 17:41

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.