更新:无法在添加到购物车事件时检测自定义购物车商品数据。
检查购物车项目将允许您防止购物车项目同时具有 $cart_item['default-engraving'] 和 $cart_item['iconic-engraving']:
add_action( 'woocommerce_check_cart_items', 'check_cart_items_custom_data' );
function check_cart_items_custom_data() {
// Initializing: set the current product type in an array
$types = [];
// Loop through cart items
foreach (WC()->cart->get_cart() as $item ){
if( isset( $item['default-engraving'] ) )
$types[] = 'default';
if( isset( $item['iconic-engraving'] ) )
$types[] = 'iconic';
}
$types = array_unique( $types );
// Check the number of product types allowing only one
if( count( $types ) > 1 ){
// Displaying a custom notice and avoid checkout
wc_add_notice( __('Only items from one product type are allowed in cart'), 'error' );
}
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试并且可以工作。
原始答案:(它不适用于您的情况,因为在添加到购物车事件中无法检测到)
以下是针对产品类型以仅允许购物车中的一种的方式:
add_filter( 'woocommerce_add_to_cart_validation', 'only_one_product_type_allowed', 10, 3 );
function only_one_product_type_allowed( $passed, $product_id, $quantity ) {
// Initializing: set the current product type in an array
$types = [ wc_get_product( $product_id )->get_type() ];
// Loop through cart items
foreach (WC()->cart->get_cart() as $item ){
// Set each product type in the array
$types[] = wc_get_product( $item['product_id'] )->get_type();
}
$types = array_unique( $types );
// Check the number of product types allowing only one
if( count( $types ) > 1 ){
// Displaying a custom notice
wc_add_notice( __('Only items from one product type are allowed in cart'), 'error' );
return false; // Avoid add to cart
}
return $passed;
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试并且可以工作。
相关:Allow only one product category in cart at once in Woocommerce