39

What would be the equivalent in Craft of ExpressionEngine's Next/Previous entry linking? I was looking at getNext() and getPrev() (and their aliases next and prev) (via the EntryModel docs), but when I try the obvious:

<a href="{{ entry.prev.url }}">Previously: {{ entry.prev.title }}</a>

I just get the current entry's data.

What piece am I missing here?

3 Answers 3

62

You are probably not using this within a craft.entries loop. Position it inside a loop or set custom parameters for your prev and next elements:

{# Set parameters for prev/next elements list #}
{% set params = craft.entries.section('blog').order('title asc') %}

{# Get the prev/next elements #}
{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

{# And make sure to only output the links if the element exists #}
{% if prevEntry %}<a href="{{ prevEntry.url }}">Previous</a>{% endif %}
{% if nextEntry %}<a href="{{ nextEntry.url }}">Next</a>{% endif %}
3
  • 1
    Thanks, I assumed that the entry already set for the URL I'm viewing would know about what came before and after. Commented Jun 12, 2014 at 13:56
  • 2
    For anyone in the same position has me who has a few entries with identical post dates (both date and time are the same), for this to work properly if ordering by post date, you also need to specify the secondary sort parameter Craft uses, which, from a quick inspect of the entries section of the CMS seems to be id (ascending). So the full criteria would be craft.entries.section(mySection).order('postDate desc, id asc').
    – Mike Vaux
    Commented Apr 6, 2016 at 9:30
  • How do I get this to work in Craft 3? I can get the prev & next urls via the paginate tag but I'm stuck on how to retrieve the entry titles... Commented Jan 11, 2019 at 17:06
20

You can set the prev.url at the top of the template, for example:

{% set criteria = {section: 'blog', order: 'postDate'} %}
{% set prev = entry.getPrev(criteria) %}

Add a link if prev is available:

{% if prev %}
   <a href="{{ prev.url }}">{{ prev.title }}</a>
{% endif %}
1
  • Sorry @Patrick, didn't see you edited your answer before I composed mine. Now pretty much identical.
    – carlcs
    Commented Jun 12, 2014 at 13:30
3

For navigating siblings in a structure there's a shortcut:

{% if entry.prevSibling %}<a href="{{ entry.prevSibling.url }}">Previous</a>{% endif %}
{% if entry.nextSibling %}<a href="{{ entry.nextSibling.url }}">Next</a>{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.