Hugo Show Related Posts By Tags

Aug 27, 2017

The following code will match posts with at least 1 similar tags.

{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
  {{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
  {{ if and $isMatchTags (ne .Permalink $currentPagePermalink) }}
    <a href="{{ .Permalink }}">{{ .Title }}</a>
  {{ end }}
{{ end }}

If you want to limit posts to a certain number.

{{ $.Scratch.Set "limit" 0 }}
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{ range .Site.Pages }}
  {{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
  {{ if and $isMatchTags (ne .Permalink $currentPagePermalink) (lt ($.Scratch.Get "limit") 5) }}
    <a href="{{ .Permalink }}">{{ .Title }}</a>
    {{ $.Scratch.Add "limit" 1 }}
  {{ end }}
{{ end }}

The following code will achieve the following:

  • Find posts which matches at least 2 tags
  • If none is found, find posts with 1 tag match and limit to 5 posts only.
{{ $.Scratch.Set "count" 0 }}
{{ $currentPagePermalink := .Permalink }}
{{ $tags := .Params.tags }}
{{/* range (where .Site.Pages "Section" "tutorials") */}}
{{ range .Site.Pages }}
{{ $isMatchTags := intersect $tags .Params.tags | len | lt 1 }}
{{ if and $isMatchTags (ne .Permalink $currentPagePermalink) }}
  <a href="{{ .Permalink }}">{{ .Title }}</a>
  {{ $.Scratch.Add "count" 1 }}
{{ end }}
{{ end }}

{{ if eq ($.Scratch.Get "count") 0 }}
  {{ $.Scratch.Set "limit" 0 }}
  {{/* range (where .Site.Pages "Section" "tutorials") */}}
  {{ range .Site.Pages }}
  {{ $isMatchTags := intersect $tags .Params.tags | len | lt 0 }}
  {{ if and $isMatchTags (ne .Permalink $currentPagePermalink) (lt ($.Scratch.Get "limit") 5) }}
    <a href="{{ .Permalink }}">{{ .Title }}</a>
    {{ $.Scratch.Add "limit" 1 }}
  {{ end }}
  {{ end }}
{{ end }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.