Custom-post-type-archive: posts sorted/filtered by year?

I have a custom-post-type wr_event whose posts are sorted by meta_key “event_date”.

Therefore I have this handy function …

function get_event_list( $latest = true, $order="ASC" ) {
    echo '<ul class="event-items">';

    $yesterday = time() - 24*60*60;
    $compare = $latest ? '>' : '<';

    $args = array(
        'post_type' => 'wr_event',
        'posts_per_page' => -1, // show all posts
        'meta_key' => 'event_date',
        'orderby' => 'meta_value_num',
        'order' => $order,
        'meta_value' => $yesterday,
        'meta_compare' => $compare
    );

    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        get_template_part( 'inc/event', 'item' );
    endwhile;
    wp_reset_postdata();
    echo '</ul>';
}

If I simply call ` all “upcoming” events are listed by their ascending event-date.

In my event-archive however I call ` so all events that have already taken place are sorted by their descending date.

My question:
How can I insert the year number between the posts in the event-archive?

Right now I have this …

- event 04-2012
- event 03-2012
- event 02-2012
- event 01-2012
- event 03-2011
- event 02-2011
- event 02-2011
- event 05-2010
- … and so on

And what I want is this …

2012
- event 04-2012
- event 03-2012
- event 02-2012
- event 01-2012

2011
- event 03-2011
- event 02-2011
- event 02-2011

2010
- event 05-2012
- … and so on

How could I insert the year number in between all events of a year?
Any clever ideas on that? I really need to find some way of doing this?

1 Answer
1

create a variable to hold the $current_year you’re outputting, and check it against each event’s year, resetting the value when you encounter an event with a different year:

$current_year="";
while ( $loop->have_posts() ) : $loop->the_post();

    // this is just a simple example of the logic,
    // you'll need to extract the year from your date key
    $this_year = get_post_meta( $post->ID, 'event_date', true );

    if( $this_year != $current_year ) :
        // new year, output the year header
        // and reset current year to this new value
        echo '<h3>' . $this_year . '</h3>';
        $current_year = $this_year;
    endif;

    echo 'event' . $this_year;

endwhile;

Leave a Comment