Related posts based on all tags?

I have posts with 3-4 tags in each. Is it possible to show related posts based on all tags?

Currently I’m using primary_tag. However, I didn’t manage to find the solution how to modify the code in order to filter by all tags.

My code:

{{#if primary_tag}}
  {{#get "posts" filter="tags:{{primary_tag.slug}}+id:-{{id}}" as |related_posts|}}
    {{#foreach related_posts}}
      {{> "post-card-suggestion"}}
    {{/foreach}}
  {{/get}}
{{/if}}

Have you seen this tutorial ?

Yes, I’ve read the tutorial, but It doesn’t work for me. It seems that there are a couple of mistakes…

They give the following example for Related posts:

{{#get "posts" limit="5" filter="tags:[{{post.tags}}]+id:-{{post.id}}" include="tags" as |related|}}
{{/get}}

I add {{#foreach related}} to the example and copy it to post.hbs

{{#get "posts" limit="5" filter="tags:[{{post.tags}}]+id:-{{post.id}}" include="tags" as |related|}}
  {{#foreach related}}
     {{> "post-card-suggestion"}}
  {{/foreach}}
{{/get}}

And nothing happens. Then I tried to implement Recently published posts.

{{#get "posts" limit="3" filter="id:-{{post.id}}" as |recents|}}

Again nothing happens. However, if we remove

post

from

filter="id:-{{post.id}}"

It works. So the final working code for Recently published posts in my case is

{{#get "posts" limit="all" filter="id:-{{id}}" as |recents|}}
  {{#foreach recents}}
    {{> "post-card-suggestion"}}
  {{/foreach}}
{{/get}}

Meanwhile, I cannot find the way to make Related posts example work.

I would suggest putting your code outside the {{#post}} {{/post}} helper in your post.hbs file.

For example, if your post.hbs file code looks like:

{{#post}}
  <h1>title here </h1>

  {{#get "posts" limit="5" filter="tags:[{{post.tags}}]+id:-{{post.id}}" include="tags" as |related|}}
  {{/get}}
{{/post}}

It will be as:

{{#post}}
  <h1>title here </h1>
{{/post}}

{{#get "posts" limit="5" filter="tags:[{{post.tags}}]+id:-{{post.id}}" include="tags" as |related|}}
{{/get}}

It does indeed sound like you have the {{#get}}{{/get}} helper calls nested inside a {{#post}}{{/post}} block.

Moving the code outside this block will result in the correct paths, or alternatively you’ll need to update the paths referencing tags and id to match the fact you’re already inside the post context… but heads-up that is tricksy because {{post.tags}} is an alias for {{posts.tags[*].slug}} :grimacing:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.