This snippet will help you synchronize all your cart items’ quantities with a given product ID quantity. When you add a second product to cart, therefore, it will get the same quantity of your product ID. Also, if you update the quantity of product ID, the other cart item quantities will automatically update accordingly.
Applications are quite niche, but it’s great to learn how to programmatically set the quantity of a cart item. As usual, each snippet of this website has got something that sooner or later you may need to use. Enjoy!
PHP Snippet: Synchronize Product ID Quantity And Other Item Quantities @ WooCommerce Cart
Note: you have to specify your “master_product_id” inside the snippet. This is the reference product. All the other products in the cart will sync with its quantity.
/**
* @snippet Sync Cart Item Quantities
* @how-to businessbloomer.com/woocommerce-customization
* @author Rodolfo Melogli, Business Bloomer
* @compatible WooCommerce 4.0
* @community https://businessbloomer.com/club/
*/
add_action( 'template_redirect', 'bbloomer_sync_cart_quantities' );
function bbloomer_sync_cart_quantities() {
if ( WC()->cart->is_empty() ) return;
$master_product_id = 20;
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $master_product_id === $cart_item['product_id'] ) {
$qty = $cart_item['quantity'];
$in_cart = true;
break;
}
}
if ( ! $in_cart ) return;
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
if ( $master_product_id !== $cart_item['product_id'] ) {
WC()->cart->set_quantity( $cart_item_key, $qty );
}
}
}
Hi Rodolfo,
Will this help with my problem which is:
Let’s say the customer puts 2 blankets in the cart. Then wonders through the website and later adds another blanket. When I extract the order, it is written down as 2+1 instead of 3. So it doesn’t register that there are 3 same items in the cart.
Best Regards, Luca
Hey Luca, no, that seems like a bug. Sorry
How can I make this work reverse?
I have a “package” product and I want it quantity to be the same as total quiantities of all other products in cart.
Thanks.
Igor, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!
Very nice, Rodolfo! I cant’ see any usage for me right now, but I loved it and will test just to see it working. Thanks!
Cool!