Grouping content from two sections by year

I currently use this code in my blog template to combine content from two different sections (‘journal’ and ‘troika’) and then arrange into year groups:

<?php 
	// function that returns the formatted date
	$callback = function($p) {
		return $p->date()->toDate('Y');
	};
	// group items using $callback
	$groupedItems = pages(['journal', 'troika'])->children()->listed()->group($callback)->flip();
	
	// output items by year
	foreach($groupedItems as $year => $itemsPerYear): ?>
	<div class="year">			
			<?php foreach($itemsPerYear->flip() as $item) : ?>
				<div>
					…content					
				</div>
			<?php endforeach; ?>
	</div>
			
	<?php endforeach ?>
<?php endif ?>

This does show posts from both grouped by year, but it shows the posts from the ‘troika’ section separately from ‘journal’. Is there a way to combine all the posts together by date? Thanks in advance!

1 Like

Sort the children before grouping them:

$groupedItems = pages(['journal', 'troika'])->children()->listed()->sortBy('date', 'desc')->group($callback); // or asc depending on sort order

Then also remove the flip() from $itemsPerYear->flip()

1 Like

Wonderful, thanks very much Sonja! That’s perfect!