How can group posts by month and year by a separate headline?

Example (output with this date format):

Dezmber 2014
– 4. Dez 2014
– 5. Dez 2014

I have a custom field (datepicker) “event_date”.

    <?php

$the_query = new WP_Query( array(
    'post_status' => 'publish',
    'meta_key'    => 'event_date',
    'orderby'     => 'meta_value'
) );

$current_header="";

while ( $the_query->have_posts() ) :
    $the_query->the_post();

    $temp_date = get_post_meta( get_the_ID(), 'event_date', true );

    if ( $temp_date != $current_header ) {
        $current_header = $temp_date;
        echo "<div class="sub_category_name_wrapper"><h5>$current_header</h5></div>";
    }

    ?>

    <div class="event_content_wrapper">
        <ul>
            <li>        
                <span><?php the_field('event_date'); ?></span>&nbsp;<span><?php the_field('event_region'); ?></span>
                <h4><?php the_title(); ?></h4>
                <br>
                <?php the_excerpt(); ?>
                <a class="content_button" href="https://wordpress.stackexchange.com/questions/174517/<?php the_permalink(); ?>">mehr</a>
            </li>
        </ul>
    </div>

<?php endwhile;

?>

2 Answers
2

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 Reply

Your email address will not be published. Required fields are marked *