问题
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.
回答1:
Try this revisited code for all product types (including product variations) :
add_filter( 'woocommerce_is_purchasable', 'purchasable_product_date_range', 20, 2 );
function purchasable_product_date_range( $purchasable, $product ) {
$date_from = (int) get_post_meta( $product->get_id(), '_availability_schedule_dates_from', true );
$date_to = (int) get_post_meta( $product->get_id(), '_availability_schedule_dates_to', true );
if( empty($date_from) || empty($date_to) )
return $purchasable; // Exit (fields are not set)
$current_date = (int) current_time('timestamp');
if( ! ( $current_date >= $date_from && $current_date <= $date_to ) )
$purchasable = false;
return $purchasable;
}
To make product variation work you need to get the parent product ID, because your variations don't have this date range custom fields:
add_filter( 'woocommerce_variation_is_purchasable', 'purchasable_variation_date_range', 20, 2 );
function purchasable_variation_date_range( $purchasable, $product ) {
$date_from = (int) get_post_meta( $product->get_parent_id(), '_availability_schedule_dates_from', true );
$date_to = (int) get_post_meta( $product->get_parent_id(), '_availability_schedule_dates_to', true );
if( empty($date_from) || empty($date_to) )
return $purchasable; // Exit (fields are not set)
$current_date = (int) current_time('timestamp');
if( ! ( $current_date >= $date_from && $current_date <= $date_to ) )
$purchasable = false;
return $purchasable;
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
来源:https://stackoverflow.com/questions/49473854/get-is-purchasable-hook-working-for-woocommerce-product-variations-too