Displaying the Next X Entries After the Current Entry
Problem
You want to display the next x
entries which appear after a given entry.
Solution
Let’s say you want to display a blog post, along with a summary of the next 3 posts (in chronological order). Here’s how you can do that, step by step:
- Retrieve the IDs of all the entries in the blog, and store them in an array.
- Find the current entry ID within the array from step 1.
- Retrieve the next 3 entry IDs after the current entry ID.
- Retrieve the entries associated with the entry IDs from step 3.
Here’s how that will look in your Twig template:
{# Step 1 #}
{% set everyId = craft.entries.section('blog').limit(null).ids() %}
{# Step 2 #}
{% set currentIndex = everyId | indexOf(entry.id) %}
{% if currentIndex != -1 %}
{# Step 3 #}
{% set nextIds = everyId | slice(currentIndex+1, 3) %}
{# Step 4 #}
{% set nextEntries = craft.entries.id(nextIds).fixedOrder(true) %}
{# Output the next 3 entries #}
{% for nextEntry in nextEntries %}
<h3>{{ nextEntry.title }}</h3>
{% endfor %}
{% endif %}
Submitted by Stephen Lewis on 1st February, 2017