php - Disabling increase stock for specific order status changes
one text
Solution:
It is impossible to get the previous order status when updating the product stock. This is because the wc_maybe_increase_stock_levels
function triggers with the hook that is executed before the hooks:
From these hooks you could have obtained the previous and new order status.
You can get around this in two steps:
- Disable the stock increase for the cancelled status (regardless of what the previous order status was)
- Set the stock increase based on one or more previous order statuses
In case you want to enable the stock increase only for orders that change the status from "other-status" (custom) to "cancelled", you can use the following code:
Replace
other-status
with the previous order status slug (without the wc- prefix).
add_action( 'init', 'custom_stock_increase' );
function custom_stock_increase() {
// disable stock increase when order status changes to "canceled"
remove_action( 'woocommerce_order_status_cancelled', 'wc_maybe_increase_stock_levels' );
// enable stock increase when status changes from "other-status" to "canceled"
add_action( 'woocommerce_order_status_other-status_to_cancelled', 'wc_maybe_increase_stock_levels' );
}
The code has been tested and works. Add it to your active theme's functions.php.
Source