How to Sync Product Quantities at Cart in WooCommerce?

Sometimes, you wish to add more than one product quantity to your cart. As soon as you add the product, the cart quantity must increase. This will bring ease in operations. So, let’s see how you can sync product quantities at cart. 

If you change one product quantity, then every other product quantity should get synced. You can make it work by learning some simple programming. The following snippet is useful to synchronize all cart quantities with a single product ID quantity. So, updating one product ID quantity will automatically update other cart item quantities. 

Here is an Image showing how your cart quantities will update:

Image of increased cart quantities after learning how to sync product quantities at Cart

PHP Snippet: Sync Product Quantities at Cart in WooCommerce

Further, remember that you need to mention master_product_id within the snippet. So, this is how every other cart quantity will sync with this given product ID.

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 do you add this snippet?

So, this is how you activate this snippet named sync product quantities at WooCommerce cart. From now onwards, if you change one product ID quantity, all other cart quantities will change. Also, it is easier to activate this function with this code. So, to apply this code, just add this PHP snippet at your child theme function.php file’s bottom. It should be placed before “?>”, if you have it there. Apart from this, CSS goes in your child theme style.css file. 

Is this snippet still valid?

So, this is how you sync product quantities at cart. So, I have applied this code on the Storefront theme and WordPress friendly hosting PHP 7.3. Let me know if everything works as expected. Share it further if you find this snippet useful for you and it had saved your time.

Also Read, How to Disable Order Email for Free Orders in WooCommerce?

How to Add Content to Order Email in WooCommerce? 

Important links: WooCommerce – https://woocommerce.com/