Home > Mobile >  No decrement on order wordpress
No decrement on order wordpress

Time:03-16

everybody !

I'm looking for a way to no decrement when an order is completed. Exemple: I got 1 T-shirt with 20 quantity. When i order, i want the number to be still 20, and not 19.)

here my hook:

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' );
    }
}

But when the order is completed, the quantity still decrease. Any idea ?

CodePudding user response:

That is because your hooked function is triggered after stock quantity is decreased.

You are trying to get previous stock quantity with

$product_stock = $product->get_stock_quantity();

But in that case this method returns already decreased value.

So, try this:

wc_update_product_stock( $product, $product_stock   $item_qty, 'increase' );
  • Related