4

I've got a channel where entries will be tagged with multiple categories. I want to use those categories to show related content for each entry.

So if an entry has cat_a, cat_b and cat_c, I want to pull in any entry that has cat_a, cat_b or cat_c, then order by how many categories they have in common – so an entry matching two of those categories would come before and entry only matching one.

Finally, I want to also sort by date. So I'd first show entries matching all 3 categories (newest first), then entries matching 2 categories (newest first) etc...

Any thoughts on how to do this?

3

Have a look at the Similar plugin https://github.com/aelvan/Similar-Craft, it should do exactly what you’re looking for.

{% set baseCriteria = craft.entries({
    order: 'postDate desc',
    limit: 5,
}) %}

{% set similarEntries = craft.similar.find({
    element: entry,
    context: entry.myCategoriesField,
    criteria: baseCriteria,
}) %}
  • Thanks Carl, looks like that'll do it! It doesn't work with eager loading which is a shame, but otherwise looks great. – Frank Harrison Aug 23 '17 at 11:24

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.