0

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,
        ),
    )
2
  • does it work without date_query?
    – birgire
    Commented May 18, 2022 at 16:25
  • So, I tested it further up the functions file and it worked, with the date query. For some reason when it is lower down in the functions file it doesn't work. Hmm Commented May 18, 2022 at 16:47

1 Answer 1

0

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.

2
  • I have edited my question with something else I tried. Is that what you meant? Commented May 18, 2022 at 15:47
  • Sure - but I would drop the leading zero (use 1, not 01) as I'm not sure that's valid in this context.
    – vancoder
    Commented May 18, 2022 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.