Woocomerce 在将另一个特定项目添加到购物车时删除特定的购物车项目 [英] Woocomerce Remove a specific cart items when adding to cart another specific items

查看:25
本文介绍了Woocomerce 在将另一个特定项目添加到购物车时删除特定的购物车项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处提供了解决方案 在 Woocommerce 中将特定产品添加到购物车时删除特定的购物车项目 适用于一个产品 ID.

Provided solution here Remove a specific cart item when adding to cart a specific product in Woocommerce works perfect for one product id.

有没有办法对多个 id 执行此操作?

Is any way to do this for multiple id's?

推荐答案

Update 2 :以下代码适用于多个产品 ID:

Update 2 : The following code will work for multiple product IDs:

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) {

    // Set HERE your targeted product ID
    $target_product_ids1 = array(31, 32);
    $target_product_ids2 = array(33, 34);
    // Set HERE the  product ID to remove
    $item_id_to_remove1 = 37;
    $item_id_to_remove2 = 53;

    // Initialising some variables
    $has_item1 = $has_item2 = $is_product_id1 = $is_product_id2 = false;

    foreach( WC()->cart->get_cart() as $key => $item ){
        // Check if the item to be removed 1 is in cart
        if( $item['product_id'] == $item_id_to_remove1 ){
            $has_item1 = true;
            $key_to_remove1 = $key;
        }
        // Check if the item to be removed 2 is in cart
        if( $item['product_id'] == $item_id_to_remove2 ){
            $has_item2 = true;
            $key_to_remove2 = $key;
        }

        // Check if we added to cart any targeted product IDs 1
        if( in_array( $product_id, $target_product_ids1 ) ){
            $is_product_id1 = true;
        }

        // Check if we added to cart any targeted product IDs 2
        if( in_array( $product_id, $target_product_ids2 ) ){
            $is_product_id2 = true;
        }
    }

    if( $has_item1 && $is_product_id1 ){
        WC()->cart->remove_cart_item($key_to_remove1);

        // Optionaly displaying a notice for the removed item:
        wc_add_notice( __( 'The product 1 "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
    }

    if( $has_item2 && $is_product_id2 ){
        WC()->cart->remove_cart_item($key_to_remove2);

        // Optionaly displaying a notice for the removed item:
        wc_add_notice( __( 'The product 2 "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中.经测试有效.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于Woocomerce 在将另一个特定项目添加到购物车时删除特定的购物车项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆