I want to increase the quantity of a product on the cart page of WooCommerce if the product already exists on the cart.
I tried this piece of code
if ( 'same_product_added_to_cart' === $customer_gets_as_free ) {
foreach ( $main_product_id as $main_product_single ) {
$main_product_single = intval( $main_product_single );
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $cart_item['product_id'] === $main_product_single ) {
// Get the current quantity
$current_quantity = $cart_item['quantity'];
// Increase the quantity by one
$new_quantity = $current_quantity + 1;
// Update the cart with the new quantity
WC()->cart->set_quantity( $cart_item_key, $new_quantity );
break; // Exit the loop since we have found our product
}
}
}
}
It did not work, instead, it triggered an infinite amount of loops giving an error. What am I doing wrong here. and also the add_to_cart() function gives an error of the same type.
Normally, WooCommerce does that by itself if there is no different custom cart item data added to the cart item on add to cart.
There are mistakes and missing steps in your code.
Here is the way to merge duplicated products (cart items):
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
Addition (based on the OP comment):
The following will target specific defined product(s). If a specific product is already in cart, increase the quantity by one (define your product(s) ID(s) below):
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.