2

I am trying to figure out how I can put categories to use, and I need some help.

I have created a category group called "group1", and 2 catogories inside called "cat1" and "cat2". and I have added the catogorie field to some articles in a structure so that I have a few linked to both cat1 and cat2.

My goal simply to make a forloop listing the catogorie title of both cat1 and cat2, and create an UL with the entry.title of the entries in each catogorie.

This is my code:

{% for cat in craft.categories.group('group1') %}
    <p>{{ cat.title }}</p>
    {% for entry in craft.entries.section('structure').level(3).relatedTo(cat) %}
        <ul>
            <li>{{ entry.title }}</li>
        </ul>
    {% endfor %}
{% endfor %}

This gives me the two catogorie titles, but no entry titles. I dont think I understand how to use the related to group part. Would really appreaciate some help figuring this one out.

3

You're being a little too specific in your entries call. Chances are you don't have any entries at level 3. And, what happens if you have entries in a channel that might be related to those categories?

  {% for cat in craft.categories.group('group1') %}
  <p>{{ cat.title }}</p>
  {# You can just query all the entries in the system. Or you can provide other criteria. #}
  {% set relatedEntries = craft.entries.relatedTo(cat) %}
  {# Why the variable above? Well we can check the length and see if we have responses and avoid injecting empty HTML tags into our code #}
  {% if relatedEntries|length %}
    <ul>
    {% for entry in relatedEntries %}
      <li>{{ entry.title}}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endfor %}

You can provide additional criteria to the query for entries too. The above searches the whole system for any related entries. This would just query any items in the 'structure' section for related entries to the category.

{% set relatedEntries = craft.entries.section('structure').relatedTo(cat) %}
  • I was a bit to speciffic. in my case this solved it. {% set relatedEntries = entry.children.relatedTo(cat) %} – laden May 18 '17 at 10:54
3

Your code is only listing entries in the structure that are nested inside 2 parent entries. Try this:

{% for entry in craft.entries.section('structure').relatedTo(cat) %}

Also, your <ul> is inside your for loop, it should be:

<ul>
    {% for entry in craft.entries.section('structure').relatedTo(cat) %}`
    <li>{{ entry.title }}</li>
    {% endfor%}
</ul>

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.