完成 WooCommerce 订单后增加库存(而不是减少)?

Increase stock (not decrease) after completed WooCommerce orders?

我目前正在使用 WooCommerce 开发一个 WordPress 项目,我需要一个非常具体的功能 (未包含在 WooCommerce 中)

订单完成后如何增加库存而不是减少库存?

到目前为止,我发现我可能需要使用 Woocommerce API 才能完成 WC_AJAX::increase_order_item_stock();。不过我不太习惯使用复杂的 PHP...

你有什么思路可以做到这一点吗?
也许使用插件(我没有找到)?还是使用原始代码?

总结一下:我想为一家餐厅建立一个网站,该网站具有库存管理功能,并且可以让厨师从不同的供应商处订购商品。因此,当厨师从 woocommerce 商店页面订购商品时,购买商品的库存必须增加而不是减少。

我尝试了不同的方法,例如 'WC Vendors' 或 'Marketplace' 但没有成功……

谢谢。

你可以尝试这个自定义函数挂接到 woocommerce_order_status_completed 操作挂钩,当状态设置为完成:

add_action( 'woocommerce_order_status_completed', 'action_on_order_completed' , 10, 1 );
function action_on_order_completed( $order_id )
{
    // Get an instance of the order object
    $order = wc_get_order( $order_id );

    // Iterating though each order items
    foreach ( $order->get_items() as $item_id => $item_values ) {

        // Item quantity
        $item_qty = $item_values['qty'];

        // getting the product ID (Simple and variable products)
        $product_id = $item_values['variation_id'];
        if( $product_id == 0 || empty($product_id) ) $product_id = $item_values['product_id'];

        // Get an instance of the product object
        $product = wc_get_product( $product_id );

        // Get the stock quantity of the product
        $product_stock = $product->get_stock_quantity();

        // Increase back the stock quantity
        wc_update_product_stock( $product, $item_qty, 'increase' );
    }
}

The code works with simple or variables products that have their own stock management enabled. So may be you might need to make some changes on it, depending on your WooCommerce settings. This is just an example that gives you an idea, a way…

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

此代码不会在 WooCommerce 版本 2 上引发错误。6.x,并且应该有效。