Search code examples
phpwordpressadvanced-custom-fieldscustom-post-typewordpress-rest-api

WP_Query can't filter between two dates


I am using WP Rest API as backend of a mobile app. The app is a simple todo list, where tasks have a task_date.

I came up with the following:

  • Task is a custom post type
  • task_date is a field created with ACF (date selector with Ymd format)

So, i am creating this endpoint

GET /calendar - params { date_from, date_to} (params are Ymd string dates).

which should return all tasks with task_date between date_from and date_to.

This is the code i've came up with:


    public function get_task_calendar($req){

        $params = $req->get_params();


        $args = array(
            'post_type' => 'task',
            'fields' => array("ID", "post_title"),
            'meta_query' => array(
                'relation' => 'AND',
                array(
                    'key' => 'task_date',
                    'compare' => '>=',
                    'value' => date("Ymd", strtotime($params["date_from"])),
                    'type' => 'DATE'
                ),
                array(
                    'key' => 'task_date',
                    'compare' => '<=',
                    'value' => date("Ymd", strtotime($params["date_to"])),
                    'type' => "DATE"
                )
            )
        );

        $query = new WP_Query($args);

        $results = $query->get_posts();

        return $results;


    }

I've seen other solutions where it is used a BETWEEN operator instead, but i had no success either. Unfortunately, ACF doesn't allow us to store this field as timestamp (which would be easier to compare), so i am casting it inside the query. Any help would be appreciated.

Thanks in advance,


Solution

  •             array(
                    'key' => 'task_date',
                    'compare' => '>=',
                    'value' => date("Ymd", strtotime($params["date_from"])),
                    'type' => 'DATE'
                ),
    

    Can you try and leave out 'type' => 'DATE'?

    https://developer.wordpress.org/reference/classes/wp_meta_query/#accepted-arguments says,

    The type DATE works with the compare value BETWEEN only if the date is stored at the format YYYY-MM-DD.

    I’m guessing that is probably the same for >=/<=.

    ACF stores the value as YYYYMMDD however, so if you do a plain string comparison here, that should work.