Increase stock when ordering in WooCommerce

I am currently working on a WordPress project using WooCommerce and I need a really specific feature (not included in WooCommerce):

How to increase stock when an order is complete instead of decreasing it ?

What I have found so far is that I might need to use Woocommerce API in order to accomplish that WC_AJAX::increase_order_item_stock();. Nevertheless I am not really comfortable using complex PHP…

Do you have some lines of thinking to accomplish this?
Maybe using a plugin (which I did not find)? Or with raw code?

To sum up everything: I want to build a website for a restaurant with an inventory management and the possibility for cooks to order goods from different suppliers. So when a cook order something from the woocommerce shop page, purchased items’s inventory have to increase and not decrease.

I have tried different things like ‘WC Vendors’ or ‘Marketplace’ but without success…

Thanks.

Answer

You could try This custom function hooked in woocommerce_order_status_completed action hook, that will increase back each product stock with the items quantity of this order when status is set to 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…

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code don’t throw errors on WooCommerce version 2.6.x, and should work.

Leave a Reply

Your email address will not be published. Required fields are marked *