Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Last active October 30, 2018 17:07
Show Gist options
  • Save harisrozak/8d64c8b2a2050fe0793118e7a80cfaea to your computer and use it in GitHub Desktop.
Save harisrozak/8d64c8b2a2050fe0793118e7a80cfaea to your computer and use it in GitHub Desktop.
WooCommerce Booking, get the unavailable rentals by date
<?php
$dateTimeStart = new DateTime($timestamp_start);
$dateTimeEnd = new DateTime($timestamp_end);
$unavailable_ids = wc_booking_unavailable_rentals_by_date($dateTimeStart, $dateTimeEnd);
// get all unavailable rentals by date
function wc_booking_unavailable_rentals_by_date($dateStart, $dateEnd) {
$filtered_rentals = array();
$unavailable_ids = array();
$start = array(
'y' => $dateStart->format('Y'),
'm' => intval($dateStart->format('m')),
'd' => intval($dateStart->format('d')),
'ymd' => $dateStart->format('Ymd')
);
$end = array(
'y' => $dateEnd->format('Y'),
'm' => intval($dateEnd->format('m')),
'd' => intval($dateEnd->format('d')),
'ymd' => $dateEnd->format('Ymd')
);
// WP Query
$the_query = new WP_Query(array(
'post_type' => 'product',
'posts_per_page' => -1, // -1 mean show all data
'post_status' => 'publish',
));
// loop
while ($the_query->have_posts()) : $the_query->the_post();
$id = get_the_ID();
$title = get_the_title();
$product_obj = new WC_Product_Booking($id);
$avability = $product_obj->get_availability_rules();
foreach ($avability as $root) {
if(! isset($root[1]) || ! is_array($root[1])) continue;
foreach ($root[1] as $year => $value) {
if($year >= $start['y'] && $year <= $end['y']) {
if(! is_array($value)) continue;
foreach ($value as $month => $value2) {
if(! is_array($value2)) continue;
foreach ($value2 as $day => $is_available) {
if($is_available) continue;
$date_val = new DateTime("$year-$month-$day");
if(! isset($filtered_rentals[$id]['name'])) {
$filtered_rentals[$id]['name'] = $title;
}
$filtered_rentals[$id]['date'][] = $date_val->format('Ymd');
}
}
}
}
}
endwhile;
wp_reset_query();
// filter the filtered_rentals by date range
foreach ($filtered_rentals as $key => $value) {
if(! is_array($value)) continue;
foreach ($value as $key2 => $value2) {
if($key2 != 'date') continue;
foreach ($value2 as $key3 => $dateint) {
if($dateint >= $start['ymd'] && $dateint <= $end['ymd']) {
$unavailable_ids[] = $key;
break;
}
}
}
}
return $unavailable_ids;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment