I have a WooCommerce site where adding a product to the cart is typically done by clicking on a button or link with a URL that points to the /cart/
URL with the query string ?add-to-cart=7&quantity=1
appended onto it. Like this:
http://example.com/cart/?add-to-cart=7&quantity=7
The number add-to-cart=7
is the ID of the product and, obviously, quantity=1
is the quantity of the product to add to the cart.
That all works fine.
The problem is that the user, while in the cart screen, may decide to increase or decrease the quantity. When they click "Update Cart", the quantity increases or decreases by increments of whatever the value of the quantity URL parameter is set to.
So if quantity=7
in the URL parameter and the user increases the quantity by 1 in the cart UI and clicks "Update Cart", suddenly the quantity is 15 rather than 8. That's because it's taking the original quantity value of 7 shown in the cart UI, adding 1 for the cart UI update, and then adding in 7 from the quantity
URL parameter.
What's the best way to keep this from happening? Do I need to remove the URL params from the session when the user first visits the page? Where do I even begin to do this? I started writing a filter, but I obviously don't know what I'm doing.
// Correct the updated quantity by subtracting out the URL parameter already passed from the product page
function filter_woocommerce_cart_item_quantity( $product_quantity, $cart_item_key, $cart_item ) {
if(isset($_REQUEST['quantity']) && ($_REQUEST['quantity'] != "")) {
$product_url_param_qty = $_REQUEST['quantity']
$product_quantity = $product_quantity - $product_url_param_qty
}
return $product_quantity;
};
// add the filter
add_filter( 'woocommerce_cart_item_quantity', 'filter_woocommerce_cart_item_quantity', 10, 3 );