Display posts between two dates meta_query wordpress

2.7k views Asked by At

I have two custom fields (advanced custom fields) of "start_date" and "end_date", I want to filter the projects that are between the two given dates, here is what i've tried:

 array(
            'key' => 'date_start',
            'value' => array($date_start_formatted, $date_end_formatted),
            'type' => 'DATE',
            'compare' => 'BETWEEN',
        ),

and also:

       array(
             'key' => 'date_start',
             'type' => 'DATE',
             'value' => $date_start_formatted,
             'compare' => '>=',
         ),

        array(
            'key' => 'date_end',
             'type' => 'DATE',
             'value' => $date_end_formatted,
             'compare' => '<=',
         ),

Is there a way to find all the project dates that fit between these two dates, for example,

date_start filter = 05.05.2020 and date_end filter = 20.05.2020 

but project is date_start = 04.05.2020 and date_end is = 19.05.2020

additionally project 2 has date_start of 07.05.2020 but end date is = 22.05.2020

(basically finds all projects that have some dates between the two filtered)

two projects show up because they have some dates that are between the given filters

1

There are 1 answers

2
Tami On

ACF suggests you do this to get results between two dates

$args  = [
   'post_type'      => 'project',
   'meta_query'     => [
      [
         'key'     => 'event_dates',
         'value'   => [$start_date, $end_date],
         'compare' => 'BETWEEN',
         'type'    => 'DATE'
      ]
   ]
];

In your example, you should save the two dates in an array for each event. It's an extra meta but that would be the way to do it.

ACF docs: https://support.advancedcustomfields.com/forums/topic/date-format-and-wp_query/