Search code examples
phpwordpresswoocommercecartproduct-quantity

override the product quantity of existing already product in cart -Woocommerce


I have tried a lot to override the existing product quantity in the cart but nothing.

Actually I have this code:

add_action('woocommerce_add_to_cart', 'add_to_cart_qty', 10, 6 );
function add_to_cart_qty( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){

    $real_product_id = $variation_id > 0 ? $variation_id : $product_id;

    $product = wc_get_product($real_product_id);
    $product_stock = $product->get_stock_quantity();

    // Zero or negative stock (remove the product)
    if( $product_stock <= 0 && $product->get_manage_stock() ){
        WC()->cart->remove_cart_item( $cart_item_key );
        return;
    }

    if( $quantity > $product_stock && $product->get_manage_stock() ){
        WC()->cart->set_quantity( $cart_item_key, $product_stock );
    }
}

that sets the maximum available product quantity when product is added to cart. But I will need also to act in cart page when customer change the item quantities…

I think we can handle this issue in two ways:

  • first either we remove the product on add to the cart of the same product which is already in cart
  • second way is update the quantity of existing product on add to the cart of the same product, and this should also work for variable products.

I have tried a lot of different snippet codes for this but no results.

Any help will be appreciated.


Solution

  • Using this custom function hooked in woocommerce_after_cart_item_quantity_update action hook, will avoid customer to add more than the product stock quantity when updating cart item quantity:

    add_action('woocommerce_after_cart_item_quantity_update', 'update_cart_items_quantities', 10, 4 );
    function update_cart_items_quantities( $cart_item_key, $quantity, $old_quantity, $cart ){
        $cart_data = $cart->get_cart();
        $cart_item = $cart_data[$cart_item_key];
        $manage_stock = $cart_item['data']->get_manage_stock();
        $product_stock = $cart_item['data']->get_stock_quantity();
    
        // Zero or negative stock (remove the product)
        if( $product_stock <= 0 && $manage_stock ){
            unset( $cart->cart_contents[ $cart_item_key ] );
        }
        if( $quantity > $product_stock && $manage_stock ){
            $cart->cart_contents[ $cart_item_key ]['quantity'] = $product_stock;
        }
        return $product_stock;
    }
    

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

    This code is tested and works even for product variations.