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 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.