How to remove a specific cart item when adding to cart a specific product?

前端 未结 1 413
滥情空心
滥情空心 2021-01-15 09:24

With WooCommerce, I am looking to see if it\'s possible to remove a specific item (from cart), if another specific item is in the cart.

My web shop has a free versio

相关标签:
1条回答
  • 2021-01-15 10:11

    Yes is possible with a custom function hooked for example in woocommerce_add_to_cart hook:

    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_id = 31;
        // Set HERE the  product ID to remove
        $item_id_to_remove = 37;
    
        // 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'] == $item_id_to_remove ){
                $has_item = true;
                $key_to_remove = $key;
            }
    
            // Check if we add to cart the targeted product ID
            if( $product_id == $target_product_id ){
                $is_product_id = true;
            }
        }
    
        if( $has_item && $is_product_id ){
            WC()->cart->remove_cart_item($key_to_remove);
    
            // Optionaly displaying a notice for the removed item:
            wc_add_notice( __( 'The product "blab bla" has been removed from cart.', 'theme_domain' ), 'notice' );
        }
    }
    

    This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested and works.

    0 讨论(0)
提交回复
热议问题