我有一个产品与3个变化,我只想在购物车一次从相同的变量产品的一个变化,但不想创造一个错误消息和死胡同的障碍。
如果添加了相同的产品,我想交换变体。
因此,如果客户将Product 1变体1添加到购物车中,然后他们返回并添加相同的产品但添加了不同的变体(Product 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);
}
}发布于 2020-07-16 18:42:42
下面的代码只会在购物车中“静默”地保存变量产品的最后一个变体:
add_action('woocommerce_before_calculate_totals', 'keep_last_variation_from_variable_products', 10, 1 );
function keep_last_variation_from_variable_products( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$parent_ids = array();
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Only for product variations
if ( $cart_item['variation_id'] > 0 ) {
// When a variable product exist already in cart
if( isset($parent_ids[$cart_item['product_id']]) && ! empty($parent_ids[$cart_item['product_id']]) ) {
// Remove it
$cart->remove_cart_item($parent_ids[$cart_item['product_id']]);
}
// Set in the array the cart item key for variable product id key
$parent_ids[$cart_item['product_id']] = $cart_item_key;
}
}
}代码放在活动子主题(或活动主题)的functions.php文件中。经过测试,效果良好。
https://stackoverflow.com/questions/62927294
复制相似问题