How to get Jekyll related posts to perform properly.
19 Feb 2023My Hyde configuration for this website never had the related posts working properly. I went on a mission to get related posts working, and thankfully Michelle Mac, Jekyll Related Posts had a nice short explainer.
Below is the code I settled on – largely from Michelle Mac’s website. I’ll note that the code below needs to go in the layout for posts. For me, this is _layout/post.html
.
<div class="related">
{% assign maxRelated = 5 %}
{% assign minCommonTags = 1 %}
{% assign maxRelatedCounter = 0 %}
<h2>Related Posts</h2>
<ul class="related-posts">
{% for post in site.posts %}
{% assign sameTagCount = 0 %}
{% assign commonTags = '' %}
{% for tag in post.tags %}
{% if post.url != page.url %}
{% if page.tags contains tag %}
{% assign sameTagCount = sameTagCount | plus: 1 %}
{% endif %}
{% endif %}
{% endfor %}
{% if sameTagCount >= minCommonTags %}
<li>
<h3>
<a href="{{ post.url }}">
{{ post.title }}
<small>{{ post.date | date_to_string }}</small>
</a>
</h3>
</li>
{% assign maxRelatedCounter = maxRelatedCounter | plus: 1 %}
{% if maxRelatedCounter >= maxRelated %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
</ul>
</div>