Support

Account

Home Forums General Issues Can't get CPT between 2 dates (WP_Query)

Unread

Can't get CPT between 2 dates (WP_Query)

    • henvoni

    • September 30, 2020 at 12:51 am

    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 }

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

    This is the code i’ve came up with:

    `php

    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,

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.