Support

Account

Home Forums Front-end Issues How to group posts by date

Solved

How to group posts by date

  • OK, I’m creating an event listing and want to group events by dates, i.e. like this:

    11 November 2018
    
    18:00  Event 1
    20:00  Event 2
    
    17 November 2018
    
    20:30 Event 3
    
    18 November 2018
    
    19:30 Event 4
    21:30 Event 5

    That is, have the date heading only show once per day, not for every event.
    I’ve been able to get this using WP’s the_date() function which is exactly made for this but I need a custom event start datetime field, I can’t use the post publication date.

    What’s the best way to do this with the ACF datetime field?

  • Anyone got any idea? I’d be very thankful for any help.

  • I don’t have a specific answer, but this post gives an idea of how you’d do this using an ACF date field https://wordpress.stackexchange.com/questions/174517/order-and-group-posts-by-acf-by-month-and-year

  • OK, after a long while I got back to this issue and solved it by comparing the date of the previous post in the loop with the date of the current post. The problem was that this wasn’t easily possible in templates that are retrieved with get_template_part was used. I had to use set_query_var() to make the date from the previous iteration available in the template part. Here’s my solution:

    in the main template I have:

    
    while(have_posts()):
    	the_post();
    		// retrieve event date set in ACF
    		$event_date_raw = get_field('b_date');
    		set_query_var('event_date_raw',$event_date_raw);
    		get_template_part( 'entry', 'event');
    		/*
    		assign the current date to a variable and pass it to template part in the next iteration
    		so that it can be compared with the date of the next post
    		*/
    		set_query_var('prev_date_raw',$event_date_raw);
    	}
    endwhile;
    

    and in the event sub-template I have this:

    
    // current post’s publication date by native WP functionality
    $post_date = the_date('d.m.Y','','',false);
    
    $prev_date_raw = get_query_var('prev_date_raw');
    if($prev_date_raw) {
    	// convert event date objects to datetime strings
    	$prev_date = DateTime::createFromFormat('d.m.Y H:i', $prev_date_raw);
    	$prev_date = $prev_date->format('d.m.Y');
    }
    $event_date_raw = get_query_var('event_date_raw');
    $event_date = DateTime::createFromFormat('d.m.Y H:i', $event_date_raw);
    
    if($event_date) {
    	$post_date = $event_date->format('d.m.Y');
    }
    // check whether the current post/event date is the same as the previous post’s date, and if not, print date
    if($post_date !== $prev_date) {
    ?>
    <div class="date"><?php echo($post_date); ?></div>
    <?php } ?>
    
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘How to group posts by date’ is closed to new replies.