Hexo: Previous and Next Posts Within a Category
Nexmoe July 15, 2021
This article is an AI translation and may contain semantic inaccuracies.
In the “Book” theme, I treat each category as a book, and posts inside the category as chapters.
In that case, you can’t just use site‑wide posts for previous/next navigation.
So based on Hexo: Output Posts by Category - 折影轻梦 (nexmoe.com), I wrote a snippet to output previous/next posts within the same category.
Here’s the code (comments should make it clear):
<nav class="post-nav">
<% site.categories.map(function(category){ %>
<% page.categories.map(function(page_category){ %>
<% if(page_category.name == category.name){ %> <!-- Find the matching category -->
<% let i = 0;%>
<% category.posts.sort('-date').map(function(post){ %>
<% i++; %>
<% if(post.title == page.title){ %> <!-- Find current post index -->
<% let ix = 0;%>
<% category.posts.sort('-date').map(function(post){ %>
<% ix++; %>
<% if(ix == i + 1 && post.title){ %> <!-- Previous post -->
<div class="old">
<span>Previous</span>
<a href="<%- url_for(post.path) %>"> <%= post.title %></a>
</div>
<% } %>
<% if(ix == i - 1 && post.title){ %> <!-- Next post -->
<div class="new">
<span>Next</span>
<a href="<%- url_for(post.path) %>"> <%= post.title %></a>
</div>
<% } %>
<% }) %>
<% } %>
<% }) %>
<% } %>
<% })%>
<% }) %>
</nav>
My blog is syncing to Tencent Cloud + Community. You’re welcome to join: https://cloud.tencent.com/developer/support-plan?invite_code=28l9ouqqg7vo4