Getting list of posts from primary and secondary tags

Hello I am having some trouble with Ghost v3.

I would like to make a list of posts first fetched by primary tag and then by the second tag. This code brings up the primary tag posts, however, if there are less than 3 posts with the primary tag I would like to fill the list with posts using the second tag in the article (if there is one).

{{#get “posts” filter=“tags:{{primary_tag.slug}}+id:-{{id}}” limit=“3” as |recommended|}}
{{#foreach recommended}}

Thanks!

Hey there :wave:

This seems like a very specific use of filtering with tags. Would it not be easier to filter by one specific tag for displaying posts? This could be a good use of internal tags, which don’t display on the front-end but still let you tag content. More details can be found here:

Hey David, I don’t think your suggestion will work. I have a travel blog and categorize with tags as such: [CITY] > [COUNTRY] > [DESTINATION or ITINERARY article]

So I would like to recommend articles from the same country if there are no more about that one city.

I see. Well I have something, but due to the complexity of your request this is also a bit complex:

I’ve create two #get blocks with #foreach inside each. The first gets everything with the same primary tag as the post, but is limited to a maximum of 3:

<ul>
  {{#get "posts" filter="primary_tag:{{primary_tag.slug}}+id:-{{id}}" limit="3" as |related_city|}}
      {{#foreach related_city}}
          <li class="related-city"><a href="{{url}}">{{title}}</a></li>
      {{/foreach}}
  {{/get}}

The second #get filters by the second tag, using a 0 index array reference. As well as being limited by 3 it also filters out any posts with a matching primary tag to avoid duplicates. Note the use of the classnames related-city and related-country:

  {{#get "posts" filter="tags:[{{tags.[1].slug}}]+primary_tag:-{{primary_tag.slug}}+id:-{{id}}" limit="3" as |related_country|}}
      {{#foreach related_country}}
          <li class="related-country"><a href="{{url}}">{{title}}</a></li>
      {{/foreach}}
  {{/get}}
</ul>

The last part is this CSS, which targets elements in a specific order to show and hide them depending on the amount of related-city items are shown:

.related-city ~ .related-country {
	display: none;
}

.related-city:first-of-type + .related-city + .related-country {
	display: list-item;
}

.related-city:first-of-type + .related-country,
.related-city:first-of-type + .related-country + .related-country {
	display: list-item;
}

The key part of this all working is the specific CSS targeting and the use of {{tags.[1].slug}} to target the second post tag. Granted it’s not in our documentation, but it’s very rarely used.

Hope this helps! :blush:

2 Likes