Search code examples
phpwordpresswoocommerceproductcart

WooCommerce reset quantity before adding to cart (to prevent addition)


When I add a product quantity of 3 to the cart, it's all good.

But after adding 5 more quantities to the cart, I want to quantity in the cart to be 5 and not 8.

I want the last quantity sent to override the quantity before, not add to it.

Also, I want this to behave like this only on a specific product ID.

Which hook is suitable for this?


Solution

  • You could use the woocommerce_add_to_cart hook

    In this example, product id 30 is used

    function action_woocommerce_add_to_cart ( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ) {
        // Get current product id
        $product_id = $variation_id > 0 ? $variation_id : $product_id;
    
        // Specific product ID, compare
        if ( $product_id == 30 ) {
            // Set quantity
            WC()->cart->set_quantity( $cart_item_key, $quantity );      
        }
    }
    add_action( 'woocommerce_add_to_cart', 'action_woocommerce_add_to_cart', 10, 6 );