Sync Product Quantities @ Cart

woocommerce sync cart item quantities

This snippet will help you synchronize all your cart items’ quantities with a given product ID quantity. When you add a second product to the 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 a 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!

Sync Product Quantities @ Cart
Based on the snippet example below, whenever I change the quantity of product ID = 20 (called 2 Simple), all the other products’ quantity will be synced.

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
 * @author        PHP - Stackoverflow
 * @compatible    WooCommerce 4.0
 */
   
add_action( 'template_redirect', 'phpsof_sync_cart_quantities' );
   
function phpsof_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 );
		}
	}     
}

Where to add this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (before “?>” if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files – if you need more guidance, please take a look at my free video tutorial “Where to Place WooCommerce Customization?”

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with the Storefront theme, the WooCommerce version listed above, and a WordPress-friendly hosting on PHP 7+.

If you think this code saved you time & money, feel free to join 10,000+ WooCommerce Weekly subscribers for blog post updates or 250+ PHP Stackoverflow supporters for 365 days of WooCommerce benefits. Thank you in advance 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *