Show Similar Posts in Jekyll Using Liquid Magic
1 minute
If you like to create a section where users can find similar posts in Jekyll, you can adopt from my approach.
First, create a file related.html and add in the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{% assign maxRelated = 3 %}
{% assign minCommonTags = 1 %}
{% assign maxRelatedCounter = 0 %}
{% assign related_posts = "" %}
{% for post in site.posts %}
{% assign sameTagCount = 0 %}
{% for tag in post.tags %}
{% if post.url != page.url and page.tags contains tag %}
{% assign sameTagCount = sameTagCount | plus: 1 %}
{% endif %}
{% endfor %}
{% if sameTagCount >= minCommonTags %}
{% capture include_postbox %}{% include postbox.html %}{% endcapture %}
{% assign related_posts = related_posts | append: include_postbox %}
{% assign maxRelatedCounter = maxRelatedCounter | plus: 1 %}
{% if maxRelatedCounter >= maxRelated %}
{% break %}
{% endif %}
{% endif %}
{% endfor %}
{% if maxRelatedCounter > 0 %}
<div class="row listrecent">
{{ related_posts }}
</div>
{% endif %}
Then, in your post layout, you can include this file where you want the related posts to appear:
1
2
3
4
5
6
7
{% capture related_content %}{% include related.html %}{% endcapture %}
{% if related_content contains 'listrecent' %}
<hr class="relline">
<h1 class="related">{% t post.also %}</h1>
{{ related_content }}
<hr>
{% endif %}
And that’s it! This will display a section with similar posts based on shared tags, limited to a maximum number of related posts and a minimum number of common tags. You can adjust the maxRelated and minCommonTags variables to fit your needs.
With reference from this post.
(Updated: )
Also Read
Jekyll Paginate V2 categories auto pages and normal generation
For some reasons, when I was using Jekyll Paginate V2, I had problems getting both the auto pages and generation to work seamlessly together. Auto pages always seem to give...