Search code examples
phpwordpresswoocommercecartproduct-variations

Remove specific product variation from cart in WooCommerce


I want to remove a variation product from the cart in wordpress, woocommerce.

I'm able to remove a simple product but not a variation product. With this code I can remove a simple product. I have tried passing in both the variation id and the parent variation id. I have no idea why its not working, would appreciate if some got a clue.

$product_cart_id = WC()->cart->generate_cart_id( $aCurrentUserDataItem->id );
$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );

Solution

  • You can also use a foreach loop as follow to target and remove a specific variation id from cart:

    $remove_variation_id = 41; // The variation id to remove
    
    // loop through cart items
    foreach ( WC()->cart->get_cart() as $item_key => $item ) {
        // If the targeted variation id is in cart
        if ( $item['variation_id'] == $remove_variation_id ) {
            WC()->cart->remove_cart_item( $item_key ); // we remove it
            break; // stop the loop
        }
    }
    

    Tested and works.