4

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?

  • Hi and welcome, I'm not sure if I interpreted well your original question. Please confirm, and if not, edit it again :) – brasofilo Nov 27 '12 at 1:57
  • @brasofilo you interpreted it correctly. Any chance you can help me out? – Mister Melotte Nov 27 '12 at 21:11
  • Sorry, I don't have a similar setup to test this scenario. Take a look at this search query. Confirm the Custom Fields arguments for the query. Maybe format the query_posts like this. Or, more important, use WP_Query instead. Have you checked ACF forums? – brasofilo Nov 27 '12 at 22:44
3

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;

?>
  • Thanks a lot, this was the help I was looking for. Now it looks so simple. That's what you get when designers want to develop. – Mister Melotte Dec 7 '12 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.