Group custom post type posts by month

Question

I need help grouping posts by month+year (sorted by the date the posts were published a), when in result I’d have something like this:

November 2019
Event 1
Event 2
December 2019
Event 3
Event 4
January 2020
Event 5
...

I’ve been looking everywhere for a solution, but I still can’t figure it out. I’m using a code, I found here, which I guess should do the job, but I’m not so fluent in php, so I can’t figure out how to get the date at $current_year and $current_month. Right now it’s looking like this:

        <?php
    $current_year = $current_month = '';

    while ( have_posts() ) :
        the_post();

        $last_year = $current_year;
        $last_month = $current_month;

        $current_year = date( 'Y', strtotime( get_post_meta( get_the_ID(), '_date', true ) ) );
        if ( $last_year != $current_year ) {
            $last_month = '';
        }
        $current_month = date( 'F', strtotime( get_post_meta( get_the_ID(), 'event_startdate', true ) ) );
?>
    <?php if ( $last_year != $current_year ) : ?><h2><?php echo $current_year; ?></h2><?php endif; ?>
    <?php if ( $last_month != $current_month ) : ?><h3><?php echo $current_month; ?></h3><?php endif; ?>
           <?php get_template_part( 'template-parts/content-pasakumi', get_post_type() ); ?>
<?php endwhile; ?>

with the functions.php containing this:

add_action( 'pre_get_posts', function ( $query ) {
    if ( is_post_type_archive( 'pasakumi' ) && $query->is_main_query() ) {
        $query->set( 'post_type', 'pasakumi' );
        $query->set( 'orderby', 'date' );
        $query->set( 'order', 'ASC' );
    }
} );

(the custom post type is pasakumi)

Any help would be appreciated!

0
, , dans_j 2 years 2019-12-02T05:37:49-05:00 0 Answers 114 views 0

Leave an answer

Browse
Browse