Home › Forums › General Issues › Past Events Page, Display Posts by DatePicker Year › Reply To: Past Events Page, Display Posts by DatePicker Year
Hi @codeview
You can achieve this by adding in some simple logic to sort the posts into another array which is divided by years like so:
<?php
$years = array();
if( $posts )
{
foreach( $posts as $post )
{
setup_postdata( $post );
// get date
$date = date_create( get_field('enddate') );
// get year
$year = date_format($date,'Y');
// create new year if not already exists
if( !isset( $years[ $year ]) )
{
$years[ $year ] = array(
'title' => 'Events from ' . $year,
'posts' => array()
);
}
// add post to year
$years[ $year ]['posts'][] = $post;
}
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
}
if( $years )
{
foreach( $years as $year )
{
echo '<h3>' . $year['title'] . '</h3>';
if( $year['posts'] )
{
foreach( $year['posts'] as $post )
{
setup_postdata( $post );
// get date
$date = date_create( get_field('enddate') );
echo '<h3><a href="';
the_permalink();
echo '">';
the_title();
echo '</a></h3>';
echo date_format($date,'F d, Y');
}
}
}
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
}
?>
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’re working hard on Advanced Custom Fields PRO 6.0, and Beta 1 is now available 🚀
— Advanced Custom Fields (@wp_acf) August 12, 2022
Featuring improved performance for Repeater fields with large datasets, and a new generation of ACF Blocks.
Let’s take a look 🧵https://t.co/Befre3kFAo
© 2022 Advanced Custom Fields.
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 Cookie Policy. If you continue to use this site, you consent to our use of cookies.