How to create a related posts section

Am trying to create a set of related posts on my site. What is the best way to approach this. I have tried some methods I found online but some how it let’s my build failed. Jekyll related posts just literally the most recent posts as related,which isn’t what I want.

2 Likes

Where are you hosting your site? If it’s with GitHub Pages then it will only show the latest posts and not “related” as LSI is disabled.

As per Jekyll’s docs:

If the page being processed is a Post, this contains a list of up to ten related Posts. By default, these are the ten most recent posts. For high quality but slow to compute results, run the jekyll command with the --lsi (latent semantic indexing) option. Also note GitHub Pages does not support the lsi option when generating sites.

If you can install plugins there are ones that can improve the related posts by matching tags and such.

And if you can’t install plugins there are pure Liquid methods that can do it, although they might increase your build time if you have a lot of posts.

2 Likes

You can add tags to your page and then filter posts with a specific tag using the where_exp filter.

frontmatter:

- tags: 
  - mytag
  - myothertag

layout:

{% for item in site.posts | where_exp: "post","post.tags contains 'mytag'" %}
  ...
{% endfor %}

Note that this is not really a related posts section… this is just a list of posts that have a specific tag.

1 Like

Frankly I didn’t know about the LSI but the webjeda tuts got the job done. Thanks.

Thank you for this. I’m using Jekyll v4.2.0 and toshimaru/jekyll-tagging-related_posts works great.

In case you’re using bundle install, here’s my setup for toshimaru/jekyll-tagging-related_posts

Gemfile

group :jekyll_plugins do
  # Other plugins ...
  gem "jekyll-tagging-related_posts"
end

_config.yaml

plugins:
  # Other plugins ...
  - jekyll-tagging-related_posts

Install dependencies with bundle install and add the following snippet to your post layout.

post layout

<! -- 
Source toshimaru/jekyll-tagging-related_posts#usage
-->
{% if site.related_posts.size >= 1 %}
<div>
  <h3>Related Posts</h3>
  <ul>
    {% for related_post in site.related_posts limit: 5 %}
    <li><a href="{{ related_post.url }}">{{ related_post.title }}</a></li>
    {% endfor %}
  </ul>
</div>
{% endif %}