I have made 2 custom product fields - availability - since when/until when. So if the current date is between these set availability dates then product is purchasable, else - it's not. Everything works perfectly however only until I post a product with a variations. Then it's like product variations ignore these custom availability fields/values and still let to add variations to cart even if current date is not between set availability dates.
function hide_product_if_unavailable( $is_purchasable, $object ) {
$date_from = get_post_meta( $object->get_id(), '_availability_schedule_dates_from' );
$date_to = get_post_meta( $object->get_id(), '_availability_schedule_dates_to' );
$current_date = current_time('timestamp');
if ( strlen($date_from[0]) !== 0 ) {
if ( ( $current_date >= (int)$date_from[0] ) && ( $current_date <= (int)$date_to[0] ) ) {
return true;
} else {
return false;
}
} else {
# Let adding product to cart if Availability fields was not set at all
return true;
}
}
add_filter( 'woocommerce_is_purchasable', 'hide_product_if_unavailable', 10, 2 );
I tried to add another filter just below woocommerce_is_purchasable
:
add_filter( 'woocommerce_variation_is_purchasable', 'hide_product_if_unavailable', 10, 2 );
But variations still ignore availability fields.
Try this revisited code for all product types (including product variations) :
To make product variation work you need to get the parent product ID, because your variations don't have this date range custom fields:
Code goes in function.php file of your active child theme (or active theme). Tested and work.