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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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