我有 1 个具有 3 个变体的产品,并且我一次只希望购物车中的 1 个变体来自同一个可变产品,但不想创建带有错误消息和死胡同的路障。
如果添加了相同的产品,我想交换变体。
因此,如果客户将产品 1 变体 1 添加到购物车,然后他们返回并添加相同的产品但不同的变体(产品 1 变体 2),我希望该函数删除变体 1 并添加变体 2。
到目前为止,这就是我想出的——我已经测试过了,它可以工作,但是如果有更简单的方法或者我可能会破坏其他东西,那就别想了
add_action( 'woocommerce_add_to_cart', 'check_product_added_to_cart', 10, 6 );
function check_product_added_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
// First Variation
$product_a = 5831;
// Second Variation
$product_b = 5830;
// Third Variation
$product_c = 5832;
// Initialising some variables
$has_item = false;
$is_product_id = false;
foreach( WC()->cart->get_cart() as $key => $item ){
// Check if the item to remove is in cart
if( $item['product_id'] == $product_b || $product_c ){
$has_item = true;
$key_to_remove = $key;
}
// Check if we add to cart the targeted product ID
if( $product_id == $product_a ){
$is_product_id = true;
}
}
if( $has_item && $is_product_id ){
WC()->cart->remove_cart_item($key_to_remove);
}
}