1

I need to be able to display entries (within one section) that share keywords. I don't care what the keywords are, just want to display the entries based on 2 or more shared keywords.

Anyone know how to go about this?

3
  • Are you adding tags (as per your title) to the entry or you want to compare two block of text for words in common?
    – Oli
    May 1 '20 at 13:26
  • Tags will be added to the entries and it's those that we need to use to link the entries together. May 1 '20 at 17:18
  • Any ideas @Oli? May 4 '20 at 9:44
2

After chatting on Discord a bit more, here's a solution in case it helps somebody:

{# Base query #}
{% set baseQuery = craft
    .entries
    .section('stories')
    .orderBy('RAND()')
    .with(['storyKeywords']) %}

{# Fetch one story at random #}
{% set baseStory = baseQuery.one() %}

Base random story: {{ baseStory.title }}<br>

{# Fetch a second story related to `baseStory` at random #}
{% set relatedStory = clone(baseQuery)
    .relatedTo({
        targetElement: baseStory.storyKeywords,
        field: 'storyKeywords'
    })
    .id('not ' ~ baseStory.id)
    .one() %}

Related Story: {{ relatedStory.title }}<br>

{% set baseKeywords = baseStory.storyKeywords %}
{% set relatedKeywords = relatedStory.storyKeywords %}

<hr>
All tags in common: {{ baseKeywords | filter((tag) => tag.title in relatedKeywords) | join(', ') }} <br>
Number of tags in common: {{ baseKeywords | filter((tag) => tag.title in relatedKeywords) | length }}
1
  • This is working like a dream! Thank you. May 5 '20 at 13:04
1

You could do the following:

{# Fetch tags from your current entry's tag field #}
{% set tags = entry.tagFieldHandle.ids() %}

{# Query entries related to your tags #}
{% set entries = craft.entries.relatedTo(tags).all() %}
1
  • Thanks but still a little confused. What IDs would I be putting here? I don't want to specify any specific tags or entries, I just need to get back 2 random entries which share at least 2 tags (ideally). Does that make sense? May 4 '20 at 14:43

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.