Sorting by date in frontend

Hey,
I have a filter / sorting menu with buttons which use the filterBy method to dynamically display a list of elements.
One of the buttons should sort my elements by date and I have no idea how to do it.

I have four filters like this

    <a href="?filter=category#anker">
        content...
    </a>

followed by my list items.

<?php 
$filterBy = get('filter'); 
$items = $site
  ->find('mypage')
  ->children()
  ->listed()
  ->when($filterBy, function($filterBy) {
      return $this->filterBy('category', $filterBy, ','); 
    })
  ->paginate(6); 

$pagination = $mypage->pagination(); 
?>

<?php foreach ($items as $item): ?>
  <div class="wrapper">content....</div>
<?php endif ?>

I want to have one filter / sorting button that sorts my items by date using a date field in the blueprint. How can you achieve this?

It’s the same, it’s just a question how you format the date for use in the URL and then use the same format when comparing to the stored value.

On a side note: It helps if you format your code properly and wrap it in backticks.

Hmm, I checked some other threads and I don’t think this is the solution I am looking for (unless I got something wrong).
I don’t want to filter my items but instead change the order they get displayed in, starting with the newest on top.

The default state is my items being shown and sorted like they are in the panel. (This is my “All” filter)

And then the user can click a button to sort in the frontend all items by date (The “Sort by newest” filter). No items should be filtered out here. The date gets set in the panel using a date field.

Is this possible?

Hey again,

I am still stuck here as I am not that advanced in PHP.
I know that I have to check my URL for a parameter and then apply the sortBy method, but I’m not sure how to do it correctly.
I tried this but it shows no items on the page.

<?php

    $filterBy = get('filter');

    $items = $site
        ->find('mypage')
        ->children()
        ->listed()
        ->when($filterBy, function($filterBy) {
            return $this->filterBy('category', $filterBy, ',');
        })
        ->when(param('filter', $filterBy) === 'newest', function($sortBy) {
            return $this->sortBy('date', 'desc');
        })
        ->paginate(3); 
    $pagination = $items->pagination();
?>

Appreciate any further help. Thanks!