Support

Account

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
    }
    
     ?>