Prev next in a loop?

I use this in my template:

echo $page->prev()->url();
echo $page->next()->url();

When I come to the end it gives a fatal error because there are no more pages. Is there a clever way to always have a next page? If no next page are found it should start over from the first one, a little bit like a repeating image slider.

I solved it. It was not that hard. Just needed to write down the question here to activate my brain cells.

if ( $page->hasPrev() ) {
    $prev = $page->prev()->url();
} else {
    $prev = $page->parents()->children()->last()->url();
}
if ( $page->hasNext() ) {
    $next = $page->next()->url();
} else {
    $next = $page->parents()->children()->first()->url();
}
1 Like

Instead of $page->parent()->children() you can also use $page->siblings(), which is easier to understand.

1 Like

Agree! I developed it a little bit more here:
http://forum.getkirby.com/t/jump-number-of-pages-back-and-forward/2146

While I don’t know if this solution covers loops as well, I would like to add this plugin by @AudioBear https://github.com/shoesforindustry/kirbycms-extensions/tree/master/plugins/uninextprev as it may be interesting for other community members looking to loop through different levels of pages.

I was looking to solve this in Kirby 3… and of course that’s how it should be done. Thanks! :smiley:

1 Like