将订单限制为 WooCommerce 中的一种产品,允许可变产品的不同变体
Limit orders to one product in WooCommerce allowing different variations of a variable product
我尝试限制客户使用 woocommerce 购买一种产品。我使用此代码:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
return $cart_item_data;
}
问题是我不能在同一可变产品中使用两种变体。我需要一些东西来限制每个订单的一种产品,但可以允许客户使用同一可变产品的多种变体。
示例:客户购买了黑色的三星 j7 智能手机,同时购买了蓝色的三星 j7。现在,如果客户想要额外添加 Sony Xperia 智能手机,他必须另外下单。
感谢任何帮助。
以下将限制添加到购物车以仅允许来自同一产品的项目(因此对于可变产品,它将允许将同一可变产品的不同变体添加到购物车) :
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 4 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = 0 ) {
if( WC()->cart->is_empty() )
return $passed;
$product = wc_get_product($product_id);
$items_in_cart = [];
if ( $product && 'variable' !== $product->get_type() ) {
$passed = false;
} elseif ( $product && 'variable' === $product->get_type() ) {
$items_in_cart[$product_id] = $product_id;
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ){
$items_in_cart[$cart_item['product_id']] = $cart_item['product_id'];
}
if( count($items_in_cart) > 1 )
$passed = false;
}
// Avoid add to cart and display an error notice
if( ! $passed )
wc_add_notice( __("Different items are not allowed on an order.", "woocommerce" ), 'error' );
return $passed;
}
代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。
我尝试限制客户使用 woocommerce 购买一种产品。我使用此代码:
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
return $cart_item_data;
}
问题是我不能在同一可变产品中使用两种变体。我需要一些东西来限制每个订单的一种产品,但可以允许客户使用同一可变产品的多种变体。
示例:客户购买了黑色的三星 j7 智能手机,同时购买了蓝色的三星 j7。现在,如果客户想要额外添加 Sony Xperia 智能手机,他必须另外下单。
感谢任何帮助。
以下将限制添加到购物车以仅允许来自同一产品的项目(因此对于可变产品,它将允许将同一可变产品的不同变体添加到购物车) :
add_filter( 'woocommerce_add_to_cart_validation', 'filter_add_to_cart_validation', 10, 4 );
function filter_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = 0 ) {
if( WC()->cart->is_empty() )
return $passed;
$product = wc_get_product($product_id);
$items_in_cart = [];
if ( $product && 'variable' !== $product->get_type() ) {
$passed = false;
} elseif ( $product && 'variable' === $product->get_type() ) {
$items_in_cart[$product_id] = $product_id;
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ){
$items_in_cart[$cart_item['product_id']] = $cart_item['product_id'];
}
if( count($items_in_cart) > 1 )
$passed = false;
}
// Avoid add to cart and display an error notice
if( ! $passed )
wc_add_notice( __("Different items are not allowed on an order.", "woocommerce" ), 'error' );
return $passed;
}
代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。