0

I'm having a search form for rentals that search locations available according to a date range.

For now, I store all reserved dates for each posts as post_meta. For exemple ;

post_id: 231 post_meta : location_reservation_start : 2022-09-02

post_id: 231 post_meta : location_reservation_end : 2022-09-08

post_id: 231 post_meta : location_reservation_start : 2022-10-02

post_id: 231 post_meta : location_reservation_end : 2022-09-02

(multiple meta_key for the same post)

There is the query :

        $start_date = $dates[0] ;
        $end_date = $dates[1] ;     
        $date_query[] = array(
            'key'     => 'location_reservation_start',
            'value' =>  array($start_date , $end_date ) ,
            'compare' => 'NOT BETWEEN',
            'type'    => 'DATE'
        ) ;
        $date_query[] = array(
            'key'     => 'location_reservation_end',
            'value' =>  array($start_date , $end_date ) ,
            'compare' => 'NOT BETWEEN',
            'type'    => 'DATE'
        ) ;
        array_push($meta_query, $date_query );

This code work if there's only one post_meta for post. As long as the post have multiple same meta_key, the NOT BETWEEN doesn't seem to work.

There is a way to make it work like that or should I store the reservation dates in a post_meta serialized as an array?

Thanks

3
  • NOT style queries are extremely expensive, even if you get this working it won't scale as your site grows, and there's a very high chance you won't be able to handle more than one or two concurrent users on that page. You also need to store the dates in a MySQL friendly format. You should avoid serialized arrays as that means math and date comparisons will no longer be available to you in WP_Query
    – Tom J Nowell
    Jul 7, 2022 at 15:20
  • What will be the best approach to get results outside the dates range? Should I have another mysql table to store reservation dates? Jul 7, 2022 at 17:49
  • instead of getting all dates that are not between A and B, it's much faster to get all dates that end before A and start after B. It results in the same information, but the query is much more efficient. We might understand it's essentially the same thing, but a database can't make the same leap of logic
    – Tom J Nowell
    Jul 8, 2022 at 15:01

0

Your Answer

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

Browse other questions tagged or ask your own question.