Is there a way to do custom sorting via the $pages->sortBy()
function?
I need to sort a bunch of pages which have a date as title (like this 04-12-2017
)
What sort of result do you get if you simply sort by title?
it sorts like this:
01-12-2017
02-11-2017
03-10-2017
31-09-2017
Hm, works for me, as long as I add a sort order:
<?php
foreach($page->children()->sortBy('title', 'desc') as $child) {
echo $child->title() . '<br>';
}
?>
Result:
24-09-2015
13-11-2016
05-04-2017
03-10-2017
01-12-2017
I think your example already shows that it is not sorting correctly. The result should be sorted descending which it is not.
Just the digits before the first -
are sorted in descending order.
Try adding 04-11-2017
to those samples. The result will be oviously wrong for both asc
and desc
.
You are right, sorry. Then I think you have to create a custom page method or a page model that converts the title to a UNIX timestamp⦠Unfortunately, there is no native sort method with a callback like the filter method.
Example with Page Model (suppose the child page template is called project.php
):
<?php
class ProjectPage extends Page
{
public function datesort()
{
return strtotime($this->title());
}
}
Then in your template, use the newly create method to sort by:
<?php
foreach($page->children()->sortBy('datesort', 'desc') as $child) {
echo $child->title() . '<br>';
}
?>