I have a post type that holds a custom meta field with a date in it. The date is stored in the format: yyyymmdd
.
On the archive page for this post type I want to create 12 separate containers, one for each month, and to display in each the posts matching the corresponding month.
My question was about looking for ideas to achieve what I wanted.
Thanks to Krzysiek Dróżdż idea, I did filter pre_get_posts and came up with this code in my archive template for the post type:
$posts_by_month = array()
while ( have_posts() ) : the_post();
// get the post meta where the date is stored in yyyymmdd format
$recurrence_date = strtotime( get_post_meta( $post->ID,'recurrence_futuredates_0_recurrence_from', true ) );
// return the month only in '1-12' format
$current_month = date( 'n', $recurrence_date );
// loop 12 months
for ( $i=1; $i<=12; $i++ ) {
if ( $current_month == $i ) {
// store all the posts for the $current_month
$posts_by_month[$current_month][] = array(
'posts' => array(
'id' => $post->ID,
'title' => get_the_title(),
'permalink' => get_permalink(),
),
);
}
}
endwhile;
// sort the month order
ksort( $posts_by_month );
// loop 12 months
for ( $i=1; $i<=12; $i++ ) {
// if there are no posts for current month, skip month
if ( $posts_by_month[$i] ) {
?>
<i><?php echo $i; ?></i>
<?php foreach ( $posts_by_month[$i] as $this_month[$i] ) : ?>
<b><?php echo $this_month[$i]['title']; ?></b><br/>
<?php endforeach;
}
}