How to link to previous/next entries in a section?

30

13

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?

Derek Hogue

Posted 2014-06-12T12:37:19.173

Reputation: 308

Answers

41

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 %}

carlcs

Posted 2014-06-12T12:37:19.173

Reputation: 31 320

1For 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 – 2016-04-06T09:30:58.023

1Thanks, I assumed that the entry already set for the URL I'm viewing would know about what came before and after. – Derek Hogue – 2014-06-12T13:56:59.690

13

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 %}

Patrick Nesbitt

Posted 2014-06-12T12:37:19.173

Reputation: 393

Sorry @Patrick, didn't see you edited your answer before I composed mine. Now pretty much identical. – carlcs – 2014-06-12T13:30:55.813