Support

Account

Home Forums General Issues Order Date Fields By Year, Then Month Reply To: Order Date Fields By Year, Then Month

  • UPDATE. I found a similar question in the support pages so now my code is:

    $currentdate = date("2000-01-01");
    
        /* Order Posts based on Date Picker value */
        $posts = get_posts(array(
            'posts_per_page' => -1,
            'post_type' => 'events',
            'meta_key' => 'event_category', 
            'meta_value'=> 'Indoor Track and Field',
            'orderby' => 'meta_value_num',
            'order' => 'DESC',
                'meta_query'=> array(
                    array(
                        'key' => 'event_date',
                        'compare' => '>',
                        'value' => $currentdate,
                        'type' => 'DATE',
                ))
        ));
    
            $years = array();
    
            if( $posts ) {
    
                foreach( $posts as $post ) {
                    setup_postdata( $post );
                            
                        $date = date_create( get_field('event_date') );               
                        $year = date_format($date,'Y');
                            
                            if( !isset( $years[ $year ]) ) {
                                $years[ $year ] = array(
                                    'title' => $year,
                                    'posts' => array()
                                );
                            }
                            
                            $years[ $year ]['posts'][] = $post;
                            
                } wp_reset_postdata();
                
            }
    
            if( $years ) {
    
                foreach( $years as $year ) {
    
                    echo '<h2>' . $year['title'] . '</h2>';
                    echo '<ul>';
    
                    if( $year['posts'] ) {
    
                        foreach( $year['posts'] as $post ) {
                            setup_postdata( $post );
                            $date = date_create( get_field('event_date') );
                            
                                echo '<li><a href="';
                                the_permalink();
                                    echo '">';
                                    the_title();
                                    echo '</a><br>';
                                    echo date_format($date,'F d, Y');
                                    echo '</li>';
    
                        }
    
                    } echo '</ul>';
    
                } wp_reset_postdata();
    
            }

    The issue now is that the year is ordered past to present (2017, 2018, 2019) and the dates are not sorting correctly, meaning Jan, Feb, Mar, Apr…

    Can anyone help me order the year to start with 2019 and order the months by date?

    Thanks in advance.