How to List Events by Year and Month Using Advanced Custom Fields?

I have a custom post type “Kalender_item” with a custom Date Field (YYMMDD). I want to list all the posts on a page sorted by Year and Month.

For example:

Read More
  • November 2012 (all events that occure in November 2012)
  • December 2012 (all events that occure in December 2012)

And so on…

I have succeeded in ordering them like so

$kalenderItems=query_posts('post_type=kalender_item&post_status=publish&meta_key=kalender_item_datum&orderby=meta_value');

This gives me all my posts in the correct order. Now I want to group them by Month Year and display the Month Year as a title for each group.
How to group my results by year and month?

Related posts

Leave a Reply

1 comment

  1. This should get you started:

    <?php
    
    $the_query = new WP_Query( array(
        'post_type'   => 'kalender_item',
        'post_status' => 'publish',
        'meta_key'    => 'kalender_item_datum',
        'orderby'     => 'meta_value'
    ) );
    
    # This will hold what group we're in
    $current_header = '';
    
    # The Loop
    while ( $the_query->have_posts() ) :
        $the_query->the_post();
    
        # get the datum for this post
        $temp_date = get_post_meta( get_the_ID(), 'kalender_item_datum', true );
    
        # If they aren't the same, we'll start a new group, which for now
        # just means setting a new heading
        if ( $temp_date != $current_header ) {
            $current_header = $temp_date;
            echo "<h2>$current_header</h2>";
        }
    
        # ... do normal loop stuff here
    
    endwhile;
    
    ?>