Access previous image in file collection (manual sorting)


Hi, this is my first post here so please bear with me.

I am trying to use Kirby’s $file->prev() function (see here) to access the previous image in a foreach loop. The problem is that the function seems to ignore the manual sorting parameter and instead sorts by filename. Any idea what I could be missing/doing wrong?


<?php foreach($page->images()->sortBy('sort', 'asc')->offset(1) as $image): ?>
  Previous image: <?= $image->prev()->filename(); ?><br>
  This image: <?= $image->filename() ?>
<?php endforeach ?>


You need a custom method to achieve that, one that accepts a parameter, it’s the same problem for pages, have a look here:


Thank you. I’ll take a look and report back when I get this working (seems a bit daunting at the moment)…


These should work, if the last index is reached, it starts from the beginning and vice versa; if you don’t want this behaviour, you can change it, so that the functions don’t return anything once they have reached the beginning/end.

file::$methods['getNext'] = function($file, $sort='sort', $direction='asc') {
  $siblings = $file->files()->sortBy($sort, $direction );
  $index  = $siblings->indexOf($file);
  $maxIndex = $siblings->indexOf($siblings->last());
  if($index === false) return false;
  if($index === $maxIndex) return $siblings->nth(0);
  return $siblings->nth($index+1);

file::$methods['getPrev'] = function($file, $sort='sort', $direction='asc') {
  $siblings = $file->files()->sortBy($sort, $direction );
  $index  = $siblings->indexOf($file);
  $maxIndex = $siblings->indexOf($siblings->last());
  if($index === false) return false;
  if($index === 0) return $siblings->nth($maxIndex);
  return $siblings->nth($index-1);


$file = $page->files()->sortBy('sort', 'desc')->first();
$next = $file->getNext('sort', 'desc');


Handed on a silver platter. This works brilliantly, thank you so much! :heart_eyes: