Jekyll — Add Related Posts At The End Of A Post

File Structure

---
layout: article
---

Logic

Code

<h2>Enjoy Reading This Article?</h2>
<p>Here are some more articles you might like to read next:</p>

{% assign maxRelated = 5 %}
{% assign minCommonTags = 1 %}
{% assign maxRelatedCounter = 0 %}

<ul>
{% 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><a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a></li>
{% assign maxRelatedCounter = maxRelatedCounter | plus: 1 %}

{% if maxRelatedCounter >= maxRelated %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
</ul>
  • maxRelated — this is for the maximum amount of related posts to display
  • minCommonTags — this denotes the minimum amount of tags that need to be common to class posts as similar posts
  • maxRelatedCounter — this is a counter variable that will be used to determine various logic at the end of the code

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store