Your sites Log in Sign up Menu

Next / previous posts following tag?

Would it be possible to use your next / previous templating on posts to only show the next or previous post for a specific tag?


a year ago, 1 replies   developers   tags   Improve this question

Blot doesn't have an elegant way to do this right now, however you can accomplish this in an extremely inelegant way using the following technique:

  1. Generate a hidden list of every post on your site with the specific tag, e.g. 'Apple':
<div id="posts-tagged-apple" style="display:none">
{{#all_entries}}
{{#tagged.apple}}
<a href="{{{url}}}">{{title}}</a>
{{/tagged.apple}}
{{/all_entries}}
</div>
  1. Create the containers into which we will later append the next and previous links for the tag 'Apple':
<div id="next-with-tag"></div>
<div id="previous-with-tag"></div>
  1. Write some JS to determine which post is next and which post is previous in the list of posts above, then move them to the containers we created in Step 2:
<script type="text/javascript">
var next;
var previous;
var links = document.querySelectorAll('#posts-tagged-apple a');
var nextContainer = document.getElementById('next-with-tag');
var previousContainer = document.getElementById('previous-with-tag');

links.forEach(function(node, index){
   if (node.href !== "{{{entry.url}}}") return;
   nextLink = links[index + 1];
   previousLink = links[index - 1];
});

if (nextLink) nextContainer.append(nextLink);
if (previousLink) previousContainer.append(previous);
</script>

Please let me know if you have any questions about this or anything else. Note I haven't tested the code above so you may run into errors โ€“ I'd be happy to debug if you send me a live link to your implementation.

Answered a year ago ยท Improve this answer