Sort events using date, month, year values using meta_key and meta_value

328 Views Asked by At

I need to sort upcoming events ascending from today, and then past events descending from today. This is what I have so far, but I'm not sure what to set the meta-key as to make it the date sorting work (or could the meta_value be wrong?). The date, month and year values are separate so I need to somehow combine them..? Right now I have the months sorting alphabetically because it's the only thing I can get to work. :) lol

<?php if(have_posts()) : ?> 
<?php while(have_posts()) : the_post(); ?>

<?php 

$eventquery = array (
    'post_type' => 'events',
    'orderby' => 'meta_value',
    'order' => 'asc',
    'posts_per_page' => 10,
    'meta_value' => strftime("%Y/%m/%d", time()- (60 * 60 * 24) ),
    'meta_key' => '_cmb_e_month',
    'meta_compare' => '>',
    );
?>

<?php $myeventlist = new WP_Query($eventquery); ?>
<?php while ($myeventlist->have_posts()) : $myeventlist->the_post(); 
        $m_date = get_post_meta( $post->ID, '_cmb_e_date', true );
        $m_month = get_post_meta( $post->ID, '_cmb_e_month', true );
        $m_day = get_post_meta( $post->ID, '_cmb_e_day', true );
        $m_year = get_post_meta( $post->ID, '_cmb_e_year', true );
        $m_start_time = get_post_meta( $post->ID, '_cmb_e_start_time', true );
        $m_end_time = get_post_meta( $post->ID, '_cmb_e_end_time', true );
        $m_venue = get_post_meta( $post->ID, '_cmb_e_venue', true );
        $event_text     = get_post_meta($post->ID, "_cmb_e_details", true);
        $event_price = get_post_meta( $post->ID, '_cmb_e_price', true );
        $event_ticket_status = get_post_meta( $post->ID, '_cmb_e_ticket_status', true );
        $event_thumb = the_post_thumbnail('thumbnail');

?>
2

There are 2 best solutions below

2
On
$event_date=strtotime("$m_date $m_month $m_year");
$now=time();
if($event<$now) {
 echo "past event";
}
elseif($event>$now){
 echo "future event";
}
else {
 echo "now";
}
0
On

Filter the array into two separate arrays: one for past events and one for future events. Sort each array in the appropriate order. Then copy the results of the two sorted arrays into one single array.