Home Forums General Issues Order events by month


Order events by month

  • Hello,

    I need to divide the output by headline with the month.
    How could I achieve this ?


                                    //get next event from now on
                                     $args = array( 'post_type'         =>  'events',
                                    'posts_per_page'    =>  100,
                                    'orderby'           =>  'meta_value', 
                                    'order'             =>  'ASC',
                                    'meta_key'          =>  'event-date',
                                    'meta_value'        =>  date('Ymd',strtotime("today")),
                                    'meta_compare'      =>  '>=' ); 
                                    // The Query
                                    $query = new WP_Query( $args );
                                    // The Loop
                                    if ( $query->have_posts() ) {
                                        while ( $query->have_posts() ) {
                                      $meta_date = get_field('event-date');
                                      $date = date("d.m.Y", strtotime($meta_date));
                                      $city = get_field('event-city');  
                                      $location  = get_field('event-location');     
                                      $title  = get_field('event-title');    
                                      echo  '<div class="date-item">
             <div class="date"><a href="'.get_permalink().'">'.$date.'  '.$location.', '.$city.'</a></div>
             <div class="headline"><h4><a class="link-arrow" href="'.get_permalink().'">'.$title.'</a></h4></div>
                                    } else {
                                        echo 'Keine Termine vorhanden.';
                                    // Restore original Post Data
  • This is the way I generally do this. You already have the posts ordered by date. What you need to do is loop through them and when the month changes, add a new heading, so you need to alter the loop a bit.

    This is pretty basic, only showing the concept. It could get more complicated depending on what you want to do between the posts for each month.

    $last_month = '';  // empty to start
    while (have_posts()) {
        $this_month = ''; // calculate the month for this post
        if ($this_month != $last_month) {
            echo '<h2>',$this_month,'</h2>';
        $last_month = $this_month;
       // the rest of the output for your post goes here.
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.