1
votes

I have sucessfully managed to remove a product with the same bundle_id with this code

add_action( 'woocommerce_cart_item_removed', 'remove_bundled_product_from_cart', 10, 2 );
function remove_bundled_product_from_cart($removed_cart_item_key, $cart) {
    $line_item = $cart->removed_cart_contents[ $removed_cart_item_key ];
    if(isset($line_item[ 'bundle_id' ]) && !empty($line_item[ 'bundle_id' ]) ) {
        $bundle_id = $line_item[ 'bundle_id' ];
                    
        foreach( WC()->cart->get_cart() as $key => $item ){
            // Check if the item to be removed 1 is in cart
            if( $item['bundle_id'] == $bundle_id ){
                WC()->cart->remove_cart_item($key);
            }
        }
    }
}

I have then tried to apply this to approach to woocommerce_update_cart_action_cart_updated hook and also woocommerce_after_cart_item_quantity_update hook but I only managed to remove the "cart updated" notice.

After many tries, I currently have this

add_action( 'woocommerce_update_cart_action_cart_updated', 'update_cart_item_quantity', 10, 1 );
function update_cart_item_quantity( $cart_updated ){
    if( ! is_cart() ) return; // Only on cart page
    
    $set_qty = $cart->cart_contents[ $cart_updated ]['quantity'];
    $line_item = $cart->cart_contents[ $cart_updated ];
    
    if(isset($line_item[ 'bundle_id' ]) && !empty($line_item[ 'bundle_id' ]) ) {
        $bundle_id = $line_item[ 'bundle_id' ];
        
        foreach( WC()->cart->get_cart() as $key => $item ){
            if( $item['bundle_id'] == $bundle_id ){
                WC()->cart->set_quantity($key, $set_qty, true);
                $cart->cart_contents[ $key ]['quantity'] = $set_qty;
            }
        }
    }
}

All I do with the code I currently have is to remove the "cart updated" message but other than that there's no change in behavior when I update the quantity of a product with bundle_id.

How can I update the quantity of the 2nd product with the same bundle_id?