How to Link to Next and Previous Posts for Same Blog Category

Here’s an alternate version of the Liquid code snippet above. It only iterates over the categories list once, and it exits as soon as it finds a match, so it should be substantially faster, in case you are not able to use the plugin. Note that in case of multiple categories for the post, this uses the first one.

{% assign cat = page.categories[0] %}
{% assign cat_list = site.categories[cat] %}
{% for post in cat_list %}
  {% if post.url == page.url %}
  	{% assign pOffset = forloop.index0 | minus: 1 %}
  	{% assign nOffset = pOffset | plus: 2 %}
  	{% if forloop.first == false %}
  	  {% assign next_post = cat_list[pOffset] %}
  	{% endif %}
  	{% if forloop.last == false %}
  	  {% assign previous_post = cat_list[nOffset] %}
  	{% endif %}
  	{% break %}
  {% endif %}
{% endfor %}
2 Likes