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

The question:

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:

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

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 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;

?>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment