Date query for a custom meta field

You need to use a meta_query to query custom fields. If you are going to store date and time in custom fields for the purpose of ordering or comparisons, you will need to store it in the format of yyyy-mm-dd h:m:s or as a unix timestamp.

If you have two custom fields start and end and you need to get posts between a cetain start and end date, you can try the following

$args = [
    'meta_query' => [
        [
            'key' => 'start',
            'value' => '2014-05-14'
            'compare' => '>=',
            'type' => 'DATE'
        ],
        [
            'key' => 'end',
            'value' => '2015-05-07',
            'compare' => '<=',
            'type' => 'DATE'
        ],
    ],
];

$q = new WP_Query( $args );

FEW NOTES:

  • The above requires PHP 5.4+ as it uses the new short array syntax

  • The above is totally untested and might be buggy. I’m posting froma mobile device 🙂

  • Read the links I have supplied above

EDIT

For some funny reason unknown, I’ve missed the last part of your comment.

Additionally, can I have a date_query inside a meta query

The answer is no, but you can have a date and meta query within the same query, like this

$args = [
    'date_query' => [[ /* Your date related stuff */]],
    'meta_query' => [[ /* Your custom field related stuff */ ]],
];
$q = new WP_Query( $args );

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)