I would like to use something similar to the following date_query but I would like to use some custom meta fields instead of the existing post columns. For example instead of post_date_gmt I would like to query the meta key date which I have created.

In other words, I would like to be able to filter my custom_post_types using some meta fields e.g. starting_date or end_date in view them in the administration interface. I have already intercept the main WP_Query but I am not sure how I can filter a meta field instead of a post column.

Can I do that or is it better to create a meta query?

// Any posts made over a year ago
// but modified in the past month
$some_posts = new WP_Query( array(
    'date_query' => array(
        array(
            'column' => 'post_date_gmt',
            'before' => '1 year ago',
        ),
        array(
            'column' => 'post_modified_gmt',
            'after'  => '1 month ago',
        )
    ),
    'posts_per_page' => -1,
) );

1 Answer
1

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 Reply

Your email address will not be published. Required fields are marked *