问题
I am managing my stock on WooCommerce.
I would like to reduce the stock when the order status changes to a specific status for example (pending) or other status.
So I used this code:
function manageStock ($order_id, $old_status, $new_status, $instance ) {
if ($old_status === 'on-hold'){
wc_reduce_stock_levels($order_id);
}
}
add_action( 'woocommerce_order_status_changed', 'manageStock', 10, 4 );
But unfortunately does not work. Is there another way to solve this problem?
回答1:
Stock is already reduced for "on-hold", "processing" and "completed" order statuses, as you can see for wc_maybe_reduce_stock_levels() function source code, hooking the function to the following hooks:
add_action( 'woocommerce_payment_complete', 'wc_maybe_reduce_stock_levels' );
add_action( 'woocommerce_order_status_completed', 'wc_maybe_reduce_stock_levels' );
add_action( 'woocommerce_order_status_processing', 'wc_maybe_reduce_stock_levels' );
add_action( 'woocommerce_order_status_on-hold', 'wc_maybe_reduce_stock_levels' );
So don't use directly wc_reduce_stock_levels()
and replace by wc_maybe_reduce_stock_levels()
.
But on WooCommerce pending order status the function wc_maybe_increase_stock_levels()
is triggered that increase back stock levels, so we need to remove that behavior first.
Now to allow stock reduction for "pending" order status, add this code lines:
add_action('init', function() {
remove_action( 'woocommerce_order_status_pending', 'wc_maybe_increase_stock_levels' );
add_action( 'woocommerce_order_status_pending', 'wc_maybe_reduce_stock_levels' );
});
Code goes in functions.php file of the active child theme (or active theme). It should work.
Note that
woocommerce_order_status_{$status_transition_to}
is a composite hook that can be used with any other custom order status.
So for any custom order status (let say "shipped" for example), we will use:
add_action( 'woocommerce_order_status_shipped', 'wc_maybe_reduce_stock_levels' );
Code goes in functions.php file of the active child theme (or active theme). It should work.
来源:https://stackoverflow.com/questions/65976559/how-to-reduce-the-stock-for-specific-order-status-in-woocommerce