36

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?

52

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 %}
  • 1
    Thanks, I assumed that the entry already set for the URL I'm viewing would know about what came before and after. – Derek Hogue Jun 12 '14 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 Apr 6 '16 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... – erwinheiser Jan 11 '19 at 17:06
19

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 %}
  • Sorry @Patrick, didn't see you edited your answer before I composed mine. Now pretty much identical. – carlcs Jun 12 '14 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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