Solomon Closson
Solomon Closson

Reputation: 6217

How to override existing quantity already in cart?

Problem I am having here is that people go to a Product page, set a quantity on how much they want of that product and add to cart (which than takes them to the cart page). Client wants the ability to go back to the shop/product page if they want to make further changes to that product (honestly this is strange, since they can do this on the cart page, but whatever). But when people go to update the quantity on the product page, instead of updating the quantity, it adds to the existing quantity for that product.

How to get it to update the existing quantity when the quantity has been submitted more than once on the product page? Is there a woocommerce loop that I can take advantage of here?

Upvotes: 0

Views: 1670

Answers (1)

Solomon Closson
Solomon Closson

Reputation: 6217

Thanks guys, I have dug through the plugin and coded the solution below:

add_action('woocommerce_add_to_cart_handler', 'update_product_in_cart', 11, 2);

function update_product_in_cart($p, $q) {
    global $woocommerce;
    $cartItem = $woocommerce->cart->cart_contents;
    $currentProductId = $q->id;
    $wCart = $woocommerce->cart->get_cart();

    // If cart already exists, and product exists, than remove product, and add the new product to it.
    if ($wCart)
    {
        $cart_item_keys = array_keys($wCart);

        foreach($cart_item_keys as $key)
        {
            foreach($cartItem as $item)
            {
                $productItemId = $item['product_id'];
                if ($productItemId == $currentProductId)
                {
                    // If you want to empty the entire cart...
                    // $woocommerce->cart->empty_cart();
                    // If you want to remove just the product from the cart...
                    $woocommerce->cart->set_quantity($key, 0);
                }
            }
        }
    }
    // This adds the product to the cart...
    return $q;
}

This gets added to functions.php, and basically, if the product id exists in the cart, it removes the product and the return of $q adds in the new product info.

Works a charm!

Upvotes: 1

Related Questions