Home › Forums › Front-end Issues › How to group posts by date › Reply To: How to group posts by date
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 } ?>
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.