Sorting posts by year

I’ve come to an interesting scenario where I need to organize a large amount of posts by year. The aim would be to organize the posts like this:

Current year x
Newest post in year x
Older post in year x

Last year y
Newest post in year y
Older post in year y

Anyone have any ideas how to go about doing this? I thought something along the lines of creating an array by finding all posts within a year and wrapping that in a foreach function but I’m not quite sure how do go about doing that.

Have a look at this plugin for a start http://getkirby-plugins.com/bydate

1 Like

I had to do something similar and solved it like this:

<?php $allPosts = $pages->get('posts')->children()->visible()->flip() ?>

<!-- Current year label -->
<h2><?php echo date('Y') ?></h2>

<?php foreach ($allPosts as $post): ?>
  
  <!-- Year label. Show when the post's year equals neither this year nor the previous post's year -->
  <?php $prevPostYear = $post->next() != null ? $post->next()->date('Y') : null ?>
  <?php if ($post->date('Y') != date('Y') && $post->date('Y') != $prevPostYear): ?>
  <h2><?php echo $post->date('Y') ?></h2>
  <?php endif ?>
  
  <!-- Display post content -->
  <h3><?php echo $post->title()->html() ?></h3>

<?php endforeach ?>

So basically I use a regular foreach loop and inject a year label whenever the year changes. Would that work for your scenario?

1 Like

Jeez this is exactly what I was looking for, I have no idea how I missed that in the search…

Thank you so much!

Thank you too, have a look at the plug-in above too, it’s pretty perfect.