How to Add Related Posts Section in Hugo
This article will show you how to add Related Posts/Content in your Hugo website.
Adding HTML Template
Thanks to Hugo, Related Content comes default out-of-the-box. Just add
below sample code in layouts/partials/related.html
.
{{ $related := .Site.RegularPages.Related . | first 3 }}
{{ with $related }}
<h3>Related Posts</h3>
<ul>
{{ range . }}
<li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li>
{{ end }}
</ul>
{{ end }}
This snippet gets 3 related content from your posts.
And then include this partial template
in one of your default template
that
you want to show. For instance you can show these Related Content in your
_default/single.html
, so it appears on every post:
|
|
This is the actual code that I’m using for this website. If you want to look for full code check this: posts/single html, or you can look at the theme all together: Hugo Hello Friend Ng Theme.
Configure Related Content
Without any configuration set on the site, Related Content methods will use the following settings:
[related]
includeNewer = false
threshold = 80
toLower = false
[[related.indices]]
name = "keywords"
weight = 100
[[related.indices]]
name = "date"
weight = 10
It didn’t align with my needs for this site, so I tweated like below in my
config.toml
:
[related]
includeNewer = true
threshold = 80
toLower = false
[[related.indices]]
name = "title"
weight = 30
[[related.indices]]
name = "description"
weight = 30
[[related.indices]]
name = "tags"
weight = 30
[[related.indices]]
name = "date"
weight = 10
Top Level Config Options
threshold
A value between 0-100. Lower value will give more, but maybe not so relevant, matches.
includeNewer
Set to true to include pages newer than the current page in the related content listing.
toLower
Set to true to lower case keywords in both the indexes and the queries.
Config Options per Index
name
The index name. This value maps directly to a page param. Hugo supports string values (author in the example) and lists (tags, keywords etc.) and time and date objects.
weight
An integer weight that indicates how important this parameter is relative to the other parameters. It can be 0, which has the effect of turning this index off, or even negative. Test with different values to see what fits your content best.
We can see more option details in offical Hugo doc page: Configure Related Content - gohugo.io.
All done!