Order and group posts by acf by month and year

When you query the posts with orderby argument as a event_date (it could be any field with date format) the posts are ordered by date, desc or asc. So the only thing you have to do afterwards is to group them by year and month.

So:

<?php

            $posts = get_posts(array(
                'post_type' => 'post',
                'meta_key'  => 'event_date',
                'orderby'   => 'meta_value_num',
                'order'     => 'DESC'
            ));

            $group_posts = array();

            if( $posts ) {

                foreach( $posts as $post ) {

                    $date = get_field('event_date', $post->ID, false);

                    $date = new DateTime($date);

                    $year = $date->format('Y');
                    $month = $date->format('F');

                    $group_posts[$year][$month][] = array($post, $date);

                }

            }

            foreach ($group_posts as $yearKey => $years) {

                echo $yearKey;
                echo '<br>';

                foreach ($years as $monthKey => $months) {

                    echo $monthKey;
                    echo '<br>';

                    foreach ($months as $postKey => $posts) {

                        echo $posts[1]->format('d-m-Y');
                        echo '<br>';
                        echo $posts[0]->title;
                        echo '<br>';
                    }

                }

            }

        ?>

You can change the year and month format to your desire. This is just a demonstration. The same applies for HTML formatting.

Leave a Comment