gpt4 book ai didi

php - 也获取适用于 Woocommerce 产品变体的 is_purchasable Hook

转载 作者:可可西里 更新时间:2023-11-01 01:12:31 25 4
gpt4 key购买 nike

我已经制作了 2 个自定义产品字段 - 可用性 - 从何时/到何时。因此,如果当前日期在这些设置的可用日期之间,则可以购买产品,否则不能购买。一切都完美无缺,但只有在我发布具有变体的产品之前。然后就像产品变体忽略这些自定义可用性字段/值一样,即使当前日期不在设置的可用日期之间,仍然允许将变体添加到购物车。

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 );

我试图在 woocommerce_is_purchasable 下面添加另一个过滤器:

add_filter( 'woocommerce_variation_is_purchasable', 'hide_product_if_unavailable', 10, 2 );

但变体仍然忽略可用性字段。

最佳答案

为所有产品类型(包括产品变体)尝试重新访问的代码:

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;
}

要使产品变体起作用,您需要获取父产品 ID,因为您的变体没有此日期范围自定义字段:

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;
}

代码进入事件子主题(或事件主题)的 function.php 文件。测试和工作。

关于php - 也获取适用于 Woocommerce 产品变体的 is_purchasable Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com