2

I'm trying to show related entries for a single item.

I want to look up a specific tag(s), and search for any entries that share the same tag(s) then display those related items.

I've read through the documentation and searched around but couldn't find a solution.

2

Marion's answer is fine but you can also do it a different way, and move the conditional logic out of the for loop. By adding it to the query, you can ask for a specific amount of items to grab, and it won't mess up the loop.index values if you need them.

This is how I would do it.

{% set relatedEntries = craft.entries.relatedTo(tag).id('not ' ~ currentEntry.id).limit(4).find() %}

{% if relatedEntries | length %}
    {% for e in relatedEntries %}
        {# entry stuff here #}
    {% endfor %}
{% endif %}
1
  • This is easier to understand, thanks Sean! Mar 16 '15 at 16:58
1

When you have your tag[s], fetch the related entries like this:

{% set relatedEntries = craft.entries
  .relatedTo({
    targetElement: tag,
    field: 'tags'
  })
%}

This is assuming the field for the tag is tags, and the tag[s] you want to match is tag.

Then you can loop through the related entries. If you want to exclude the current entry, your loop might look like this:

{% for e in relatedEntries if e.id != currentEntry.id %}
  do things with {{e}}
{% endfor %}
0

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.