1

I need help. I am creating a category listing which I have working great. The next step is where I'm struggling a bit as I can't seem to query the related entries on a loop basis.

  1. For each "category in categories"
  2. Query Entries that are related to current category, ordered by a myField1 ASC, Only One Entry
  3. Set Image Variable to myField2
  4. Use Image Variable with current category title and URL and related entry image
  5. Loop until out of categories.

Any help would be greatly appreciated.

1 Answer 1

3

Some of your steps are unclear, but this should get you started.

{% for category in craft.categories.all() %}
    {{ category.title }}
    {{ category.url }}

    {% set entry = craft.entries
        .relatedTo(category)
        .orderBy('myField1 ASC')
        .one() %}
    {% if entry %}
        {% set image = entry.myField2.one() %}
        {% if image %}
            {{ image.url }}
        {% endif %}
    {% endif %}
{% endfor %}
4
  • Thanks for this @ben! It still doesn't seem to quite work. It throws "Impossible to access an attribute ("titleCover") on a null variable." {% set myCategoryQuery = craft.categories().group('authors').orderBy('sortName ASC') %} {% set categories = myCategoryQuery.all() %} {% for category in categories %} {% set entry = craft.entries .relatedTo(category) .orderBy('titlePublicationDate ASC') .one() %} {% set image = entry.titleCover.one() %} {{ category.url }} {{ image.url }} {{ image.altText }} {{ category.title }} {% endfor %}
    – Ben
    Jan 16 at 18:12
  • Any help would be greatly appreciated.
    – Ben
    Jan 17 at 18:05
  • 1
    I updated my answer with some extra conditions to ensure the entry and image are defined before outputting their properties.
    – Ben Croker
    Jan 17 at 20:19
  • 1
    Try adding .titleCover(':notempty:') to the entry query. Jan 18 at 6:38

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.