1

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?

Tom Smykowski
  • 25,487
  • 54
  • 159
  • 236

1 Answers1

3

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/

Nicolas Cami
  • 458
  • 1
  • 4
  • 13
  • What if you have already stored the custom field in a custom datetime format? For example, I have a datetime custom ACF field that is set to use: (j F Y, H:i:s) as a custom format. How can I compare datetimes for this specific field? I am building a plugin that needs to do a '<=' compare for the current datetime towards the custom field datetime. Since it needs to automatically remove specific custom posts from a custom post type after a given date is older then current datetime. Am I now forced to display this custom field data in a specific format? Not much info found in the codex... – SimbaClaws Jan 27 '22 at 10:35
  • I guess you can use a custom filter to specify the datetime format. The following answers give advice to work with custom date format, you should be able to make it work for datetime format with a bit of work: https://stackoverflow.com/a/29549891, https://wordpress.stackexchange.com/a/256444 – Nicolas Cami Jan 30 '22 at 10:16