WP_Query 无法在两个日期之间进行过滤

WP_Query can't filter between two dates

我正在使用 WP Rest API 作为移动应用程序的后端。该应用程序是一个简单的待办事项列表,其中任务有 task_date.

我得出以下结论:

所以,我正在创建这个端点

GET /calendar - params { date_from, date_to}(参数是 Ymd 字符串日期)。

return task_datedate_fromdate_to 之间的所有任务。

这是我想出的代码:


    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;


    }

我见过其他使用 BETWEEN 运算符的解决方案,但我也没有成功。不幸的是,ACF 不允许我们将此字段存储为时间戳(这会更容易比较),因此我将其强制转换到查询中。任何帮助将不胜感激。

提前致谢,

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

你能试着省去 'type' => 'DATE' 吗?

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

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

我猜 >=/<= 可能也是一样的。

ACF 将值存储为 YYYYMMDD 但是,因此如果您在此处进行纯字符串比较,那应该可以。