允许在WooCommerce中的一段时间内购买特定产品



基于WooCommerce答案中"只允许在选定周的时间范围内购买",我正在尝试修改代码,使其仅适用于两个产品ID,而其他所有产品都应该可以随时购买:

function is_shop_open(){
date_default_timezone_set('Europe/Paris');
$start_time = mktime('10', '00', '00', date('m'), date('d'), date('Y'));
$end_time = mktime('14', '30', '00', date('m'), date('d'), date('Y'));
$now_time = time();
$allowed_days = in_array( date('N'), array(1, 2, 3, 4, 5) );
return $allowed_days && $now_time >= $start_time && $now_time <= $end_time ? true : false;
}
add_filter('woocommerce_variation_is_purchasable', 'shop_closed_disable_purchases');
add_filter('woocommerce_is_purchasable', 'shop_closed_disable_purchases');
function shop_closed_disable_purchases( $purchasable ) {
// I am trying to apply the open and closed to two products
if (is_product('1') || is_product('2') )
return is_shop_open() ? $purchasable : false;
}
add_action( 'woocommerce_check_cart_items', 'shop_open_allow_checkout' );
add_action( 'woocommerce_checkout_process', 'shop_open_allow_checkout' );
function shop_open_allow_checkout(){
if ( ! is_shop_open() ) {
wc_add_notice( __("Notice text here"), 'notice' );
}
}
add_action( 'template_redirect', 'shop_is_closed_notice' );
function shop_is_closed_notice(){
if ( ! (is_cart() ) || is_checkout() && !is_shop_open() ) {
wc_add_notice( sprintf( '<span class="shop-closed">%s</span>',
esc_html__('Notice text here', 'woocommerce' )
), 'notice' );
}
}

但我做不到。你知道我哪里错了吗?

要只允许在特定产品的时间范围内购买,请使用以下命令:

function is_shop_open(){
date_default_timezone_set('Europe/Paris');
$start_time   = mktime('10', '00', '00', date('m'), date('d'), date('Y'));
$end_time     = mktime('14', '30', '00', date('m'), date('d'), date('Y'));
$now_time     = time();
$allowed_days = in_array( date('N'), array(1, 2, 3, 4, 5) );
return $allowed_days && $now_time >= $start_time && $now_time <= $end_time ? true : false;
}
add_filter('woocommerce_variation_is_purchasable', 'shop_closed_disable_purchases', 10, 2 );
add_filter('woocommerce_is_purchasable', 'shop_closed_disable_purchases', 10, 2 );
function shop_closed_disable_purchases( $purchasable, $product ) {
$targeted_ids = array(37, 53); // Here set the targeted products

if ( in_array($product->get_id(), $targeted_ids) ) {
return is_shop_open() ? $purchasable : false;
}
return $purchasable;
}
// Optional
add_action( 'woocommerce_check_cart_items', 'shop_open_allow_checkout' );
add_action( 'woocommerce_checkout_process', 'shop_open_allow_checkout' );
function shop_open_allow_checkout(){
$targeted_ids = array(37, 53); // Here set the targeted products

foreach( WC()->cart->get_cart() as $item ) {
if ( array_intersect( array($item['product_id'], $item['variation_id']), $targeted_ids ) && ! is_shop_open() ) {
wc_add_notice( __("Notice text here"), 'error' );
}
}
}

代码位于活动子主题(或活动主题(的functions.php文件中。

最新更新