I’m using the pre_get_posts
hook with meta_query
args to filter an archive loop by dates. Basically, there is a custom post type of “events”, and my users type in a date as a custom field for the event, in the format of “4/10/2015″ for example. If the date the user has entered is past, meaning the event already occured, then I DONT want those posts showing up in the loop. I was told to do this via a meta_query.
This is fine, but I want to compare the entered date with the current date in the format of YYYY-MM-DD, meaning I need to rearrange the user’s date input (in the format of M-D-YYYY) for comparison. I’ve tried the following code below but to no avail. Does anyone have any suggestions?
function wpd_date_meta_query( $query ) {
if( $query->is_post_type_archive( 'event' ) && $query->is_main_query() ){
function parseDate($date){
$dateAr = explode("/", $date);
if( strlen($dateAr[0]) < 2 ){
$dateAr[0] = "0" . $dateAr[0];
}
if( strlen($dateAr[1]) < 2 ){
$dateAr[1] = "0" . $dateAr[1];
}
$newDate = $dateAr[2] . $dateAr[0] . $dateAr[1];
return $newDate;
}
$meta_query = array(
array(
'key' => parseDate('Date'),
'value' => date('Ymd'),
'compare' => '>=',
'type' => 'NUMERIC'
)
);
$query->set( 'meta_query', $meta_query );
$query->set( 'meta_key', parseDate('Date') );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'wpd_date_meta_query' );