Mian Majid
Mian Majid

Reputation: 844

How compare custom fields date in wordpress?

I am doing a task for event management, I have coded a widget to display Coming or Past events in sidebar, but I can not handle the custom fields as date. following is my code, while the date is being stored as "m/d/Y". Please help me to resolve this issue. Thanks in adance

$today = date('m/d/Y');
    $args = array(
        'post_type' => 'event',
        'post_status' => 'publish',
        'meta_key' => 'event_date',
        'posts_per_page' => '5',
        'meta_query' => array(
                                array(
                                    'key' => 'event_date',
                                    'value' => $today,
                                    'compare' => '<=',
                                    'type' => 'date'
                                )
        ),
        'orderby' => 'meta_value_num',
        'order' => 'ASC'
    );

    $the_query = new WP_Query( $args );

Upvotes: 0

Views: 1678

Answers (2)

d79
d79

Reputation: 3848

While I agree with the previous answer (you should store dates in YYYY-MM-DD format), I thought I could find a workaround using a Wordpress filter, so here you go.

This should go into your functions.php file:

add_filter('posts_where', 'my_callback', 10, 2);
function my_callback( $where, $wp_query_obj ) {
    if( isset( $wp_query_obj->query['date_format'] ) ) {
        $where = preg_replace('~CAST\((.+?)\)~', "STR_TO_DATE(CAST($1), '{$wp_query_obj->query['date_format']}')", $where);
    }
    return $where;
}

And this is your query:

$today = date('m/d/Y');
$args = array(
    'post_type'      => 'event',
    'posts_per_page' => '5',
    'meta_key'       => 'event_date',
    'meta_value'     => $today,
    'meta_compare'   => '<=',
    'date_format'    => '%m/%d/%Y'
    'orderby'        => 'meta_value_num',
    'order'          => 'ASC'
);
$the_query = new WP_Query( $args );

The key here is the date_format argument I added to the query: if you don't add it the filter won't be applied.

This could work with other date formats, you only need to change the date_format argument consistent with the STR_TO_DATE MySQL function parameter format.

Upvotes: 0

johnnyd23
johnnyd23

Reputation: 1705

Date must be in YYYY-MM-DD format for the meta_query comparison to work

$today = date("Y-m-d");

Upvotes: 2

Related Questions