How to "connect" multiple products using their SKUs?
P粉466909449
P粉466909449 2024-04-05 08:53:52
0
1
3603

I want to merge the inventory of two or more products based on their SKU in WooCommerce.

Example: (Two products sharing the same inventory)

  • Transparent phone case iPhone 11 - SKU 12345
  • Personalized iPhone 11 Case - SKU 56789

(Three or more products sharing the same inventory)

  • iPhone 12 Transparent Phone Case - SKU 12345
  • Personalized iPhone 12 Case - SKU 56789
  • iPhone 12 Series Phone Case - SKU 123456

Most of our phone cases are made of clear, so I want these products to share the same inventory.

P粉466909449
P粉466909449

reply all(1)
P粉744691205

I found something on the Internet, the content is as follows:

// Get the order object
    $order = wc_get_order($order_id);

    // Loop through order items
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        $product_sku = $product->get_sku();

        // Define your SKU mappings
        $sku_mapping = array(
            'sku1' => array('sku2'),
            'sku3' => array('sku4', 'sku5'),
            'sku6' => array('sku7', 'sku8', 'sku9'),
        );

        // Check if the product SKU exists in the mapping
        if (isset($sku_mapping[$product_sku])) {
            $linked_skus = $sku_mapping[$product_sku];

            // Update the stock quantities for linked products
            foreach ($linked_skus as $linked_sku) {
                $linked_product = wc_get_product_id_by_sku($linked_sku);
                if ($linked_product) {
                    $linked_stock_quantity = get_post_meta($linked_product, '_stock', true);
                    $updated_stock_quantity = $linked_stock_quantity - $item->get_quantity();
                    update_post_meta($linked_product, '_stock', $updated_stock_quantity);
                }
            }
        }
    }
}

add_action('woocommerce_new_order', 'custom_sync_stock_on_order');
add_action('woocommerce_order_status_processing', 'custom_sync_stock_on_order');

The only problem is that when the product for sku1 is ordered, it updates the stock quantity for sku1 and sku2, but not if sku2 is ordered. Also, when I use the update button (which I did from here) it doesn't update both, only the product I'm updating.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template