search

Home  >  Q&A  >  body text

How to "connect" multiple products using their SKUs?

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

Example: (Two products sharing the same inventory)

(Three or more products sharing the same inventory)

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

P粉466909449P粉466909449222 days ago3575

reply all(1)I'll reply

  • P粉744691205

    P粉7446912052024-04-06 00:25:13

    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.

    reply
    0
  • Cancelreply