If your dates are saved in the following format, Y-m-d
, it is quite easy. Your year will stay the same, so your can then technically sort by month.
All you need is to add the correct values to the order
and orderby
parameters. You can try the following
// Query Post Type
$args = array(
'post_type' => 'events',
'post_status' => 'publish',
'meta_key' => '_eDate',
'orderby' => 'meta_value'
);
EDIT
Since you have your sorting done by the date in _eDate
, displaying the month number by a set of posts in the same month is easy. You just need to compare the previous post’s _eDate
with the current post’s _eDare
, and if they don’t match, output the month name.
EXAMPLE:
// Query Post Type
$args = array(
'post_type' => 'events',
'post_status' => 'publish',
'meta_key' => '_eDate',
'orderby' => 'meta_value'
);
$the_query = new WP_Query($args);
// Build It
if ( $the_query->have_posts() ) {
$month_array = array();
while ( $the_query->have_posts() ) {
$the_query->the_post();
$date_field = get_post_meta( $post->ID, '_eDate', true );
$month_format = DateTime::createFromFormat( 'Y-m-d', $date_field );
$month_number = $month_format->format('m');
$month_array[] = $month_number;
// Choose the format you want to display as indicated below
if ( $the_query->current_post == 0 ) // Output date id this is the first post
echo '<h2>' . $month_format->format( 'F' ) . '</h2>'; // Output month name as January
if ( $the_query->current_post != 0
&& $month_number != $month_array[$the_query->current_post - 1]
)
echo '<h2>' . $month_format->format( 'F' ) . '</h2>'; // Output month name as January
// DISPLAY YOUR POSTS AS PER NORMAL
} // endwhile
wp_reset_postdata();
} // endif