Hey. I need some help. I think this one is for @aslotta, but any help will be much appreciated.
I have created a custom post type (CPT) called “events” using the Advanced Custom Fields (ACF) plugin. Within this CPT, I have a field called “event_date”.
Now, I want to create a loop that displays events organized by year. The desired structure is as follows:
-
2024:
- Event 1
- Event 2
- …
-
2023:
- Event 1
- Event 2
- …
-
2022:
- Event 1
- Event 2
- …
To achieve this, I have a function that retrieves an array of the years:
function get_event_years() {
$years = array();
$events = get_posts(array('post_type' => 'events', 'posts_per_page' => -1));
foreach ($events as $event) {
$event_date = get_field('event_date', $event->ID);
if ($event_date) {
$year = date('Y', strtotime($event_date));
if (!in_array($year, $years)) {
$years[] = $year;
}
}
}
return implode(", ", $years);
}
Now, I need help with implementing this in a loop to get only the years. The idea is to add a second loop inside where I will query only the events in the same year.
Some help?