Prev/Next navigation across sections

I want to setup a Kirby Site with a book type structure, and I’m trying to get my head around how I create the prev/next page navigation.

Content will be posted in a random order to these sections:

Introduction
Chapter 1
Chapter 2
Chapter 3
Chapter 4

If I use <?php if ($page->hasNext()): ?> it will only navigate through pages in that section. How do I set it up so that, for example, the last post in Chapter 2 links to the first post in Chapter 3 (or wherever the next piece of content is)? Do I need to find a different way to to mark the chapters? Or create a collection of all the chapters?

You could try something in this direction:

<?php if ($page->hasNext()): ?>
  <?= $page->next()->url(): ?>
<?php elseif ($page->parent()->hasNext()): ?>
  <?php if ($next = $page->parent()->next()->children()->first()): ?>
  <?= $next->url(): ?>
  <?php endif ?>
<?php endif ?>

Checking if the parent (which should be the chapter page) has a next sibling and if that has any (first) child.

1 Like

Perfect, thank you so much! In case anyone is looking for the complete code, it’s:

		<?php if ($page->hasPrev()): ?>
			<a href="<?= $page->prev()->url() ?>"><?= $page->prev()->title() ?></a>
		<?php elseif ($page->parent()->hasNext()): ?>
			<?php if ($prev = $page->parent()->prev()->children()->last()): ?>
				<a href="<?= $prev->url() ?>"><?= $prev->title() ?></a>
			<?php endif ?>
		<?php endif ?>
		

		<?php if ($page->hasNext()): ?>
			<a href="<?= $page->next()->url() ?>"><?= $page->next()->title() ?></a>
		<?php elseif ($page->parent()->hasNext()): ?>
			<?php if ($next = $page->parent()->next()->children()->first()): ?>
				<a href="<?= $next->url() ?>"><?= $next->title() ?></a>
			<?php endif ?>
		<?php endif ?>