date_query empty results with custom post type

I am trying to use get_posts to return data between certain dates but I always get an empty result even though there is a lot of data. This is for a custom post type.

$args = array(
        'post_type' = 'bookings',
        'fields' = 'ids',
        'post_status' = 'any',
        'posts_per_page' = -1,
        'date_query' = array(
            array(
                'after' = '2022-01-01',
                'before' = '2022-06-01',
                'inclusive' = true,
            ),
        )
    );

$data = get_posts($args);
die(var_dump($data));

I also tried something like the below to get a specific date but still an empty array:

    'date_query' = array(
        array(
            'year'  = 2022,
            'month' = 01,
            'day'   = 21,
        ),
    )

Topic date-query get-posts wp-query custom-post-types Wordpress

Category Web


Assuming that you're trying to get all posts in the first half of 2022, as opposed to the first 6 days of 2022, then you need to be clearer with your before and after dates.

date_query uses strtotime behind the scenes, which will interpret your dates as Jan 1 to Jan 6. You need to either change the dates to the American format of YYYY-DD-MM, or be more specific by using arrays to express your dates instead.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.