1

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' );

1 Answer 1

0

The strtotime() function is what you need here:

$date = date( 'Y-m-d', strtotime( $date ) ); //2015-04-10 with your example

Note that you will need to do this when you save those values, not when running the query. You can't convert data that's already in the database on the fly when running a query.

Edit: I noticed an error in your meta query. This should work:

function wpd_date_meta_query( $query ) {
    if( $query->is_post_type_archive( 'event' ) && $query->is_main_query() ){
        $meta_query = array(
            array(
                'key' => '<your custom field name>',
                'value' => date( 'Y-m-d' ),
                'compare' => '>=',
                'type' => 'date'
            )
        );

        $query->set( 'meta_query', $meta_query );
        $query->set( 'meta_key', '<your custom field name>' );
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'wpd_date_meta_query' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.