Sorting pages by most recent child date

Hi! On my homepage I have a list of pages: Videos, Words, Tracks, Albums. Under each heading is a list of recent posts in each page (ie subchildren of the site children). I’d like to make it so the page with the most recent post in it is at the top of the list but I’m having trouble figuring out how to do the sorting as it’s calling on the children of each page.

Here’s what I’m playing with so far, just to get the sorting working:

<?php
$categories = pages(['videos', 'words', 'music/tracks', 'music/albums'])->sortBy(function ($page) {
  return $page->children()->listed()->flip()->limit(1)->date()->toDate();
}, 'desc');
foreach($categories as $category): ?>
  <h2><?= $category->title()->html() ?></h2>
<?php endforeach ?>

I’m getting the error Call to a member function toDate() on null so presumably the date() field of the most recent post of each page is not being called correctly. I’ve checked the date field is present in the children I’m calling in a different way and it’s all present and correct, so I’m not sure what’s not working here.

Any ideas?

With limit() you get a collection, not a single page. So use first() instead.

This would still return an error if the page has no children, though, so to be on the safe side, you would first check if that page exists, then call date() or - if you are on PHP 8 - use the null-safe operator.

1 Like

yes!! first() did the trick perfectly, thank you so much!