wordpresscodex

What is expected DATETIME format for Wordpress Codex WP Meta Query parameter?


This docs:

https://codex.wordpress.org/Class_Reference/WP_Meta_Query

Tells you can compare DATETIME values.

What is expected format of DATETIME for WP_Meta_Query?


Solution

  • From the Wordpress documentation, it seems that you should use the following string format: Y-m-d H:i:s.

    So a meta query could be:

    $meta_query_args = array(
        'relation' => 'OR', // Optional, defaults to "AND"
        array(
            'key'     => 'field_key_with_datetime',
            'value'   => '2018-03-19 08:23:25', // Y-m-d H:i:s format
            'compare' => '=',
            'type'    => 'DATETIME'
        )
    );
    $meta_query = new WP_Meta_Query( $meta_query_args );
    

    You can use the wordpress current_time function to get the current DATETIME:

    $meta_query_args = array(
        'relation' => 'OR',
        array(
            'key'     => 'field_key_with_datetime',
            'value'   => current_time( 'mysql' ), // will return something like '2018-03-19 08:23:25'
            'compare' => '=',
            'type'    => 'DATETIME'
        )
    );
    $meta_query = new WP_Meta_Query( $meta_query_args );
    

    Source: https://developer.wordpress.org/reference/functions/current_time/