Query woocommerce booking by availability date
Since the meta value is an array, it may not be possible to use WP_Meta_Query
. While I agree that using WP_Meta_Query
seems like the more elegant way to do this, I've always found this function really confusing, and since you can get the array of bookable objects, it seems like it would be straightforward to write a function like:
/** * Returns an array of bookable products according to supplied criteria * * @param int $pid the $product->ID of the bookable object * @param mixed $when a date in YYYY-MM-DD format or integer representing a day or month * @param string $type a value of 'day', 'month', or 'custom' * @param string $bookable whether the bookable object is bookable or not ('yes' or 'no') * @return array an array of bookable objects for the product */function getBookables( $pid, $when, $type, $bookable = 'yes' ) { $result = array(); // is $when in the YYYY-MM-DD format? if ( 'custom' == $type ) { // it's a custom date so convert $when to DateTime $when = DateTime::createFromFormat( 'Y-m-d', $when ); } $availability = get_post_meta( $pid, '_wc_booking_availability' ); foreach ( $availability as $a ) { if ( $a[ 'bookable' ] == $bookable ) { // is it in the YYYY-MM-DD format? if ( $when instanceof DateTime ) { // it's a custom date so use date compare $from = DateTime::createFromFormat( 'Y-m-d', $a[ 'from' ] ); $to = DateTime::createFromFormat( 'Y-m-d', $a[ 'to' ] ); if ( $when >= $from && $when <= $to ) { $result[] = $a; } } else { // it is an integer value (day or month) if ( $type == $a[ 'type' ] && ( $when >= $from && $when <= $to ) ) { $result[] = $a; } } } } return $result;}
Notice that it is probably necessary to pass the type
to the search function since even though I can distinguish YYYY-MM-DD
values from int
values, there is no easy way to distinguish month
from day
values. As such you might use the above function:
if ( $_GET[ 'when' ] && $_GET[ 'type' ] ) { $when = $_GET[ 'when' ]; $type = $_GET[ 'type' ]; $bookables = getBookables( $product->ID, $when, $type );}
Also note that if you pass the string 'no'
as the fourth parameter to the function, you can get the list of unavailable times.
Hope this helps!