Introduction:
I am encountering a challenge with a code I’ve written to automatically adjust the quantities of secondary products in WooCommerce based on the quantities of main products. However, I’m facing difficulties ensuring that changes in the quantities of main products are accurately reflected in the secondary products.
Context:
To provide context, here’s an example of a cart I have (SKU of the product, quantity):
123-T x1
123-T2 x1
123-T3 x1
79-F x2
79-F4 x2
79-F5 x2
459 x4
973-R x3
Code:
Here’s the code I’m currently using:
// add_action('woocommerce_cart_updated', 'update_related_product_quantities');
// add_action('woocommerce_before_calculate_totals', 'update_related_product_quantities');
add_action('woocommerce_cart_item_set_quantity', 'update_related_product_quantities');
function update_related_product_quantities($cart)
{
$main_product_quantities = array();
foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
$product_sku = $cart_item['data']->get_sku();
if (preg_match('/^d+-[A-Za-z]$/', $product_sku)) {
$main_product_quantities[$product_sku] = $cart_item['quantity'];
}
}
foreach ($cart->get_cart() as $cart_item_key => &$cart_item) {
$product_sku = $cart_item['data']->get_sku();
if (preg_match('/^d+-[A-Za-z]d+$/', $product_sku)) {
$main_product_sku = preg_replace('/d$/', '', $product_sku);
if (isset($main_product_quantities[$main_product_sku])) {
$new_quantity = $main_product_quantities[$main_product_sku];
//$cart->set_quantity($cart_item_key, $new_quantity);
$cart_item['quantity'] = $main_product_quantities[$main_product_sku];
}
}
}
}
Objective:
My goal is to establish a logic where the quantity of each secondary product is aligned with its corresponding main product. For instance, if I increase the quantity of product 123-T to 2, products 123-T2 and 123-T3 should also have a quantity of 2. Similarly, if I decrease the quantity of the main product, the quantities of the secondary products should decrease accordingly. Additionally, if I remove the main product, the secondary products should also be removed. Ultimately, this logic should work bidirectionally (if the quantity of a secondary product is modified, the quantities of the main product and the second secondary product modified should have the same value).
Question:
I’m uncertain if my current approach is correct or if there’s a simpler method to achieve this. Currently, changes in the quantities of main products do not affect the secondary products. I’m seeking suggestions or ideas on how to resolve this issue.
Thank you in advance for your assistance and advice!