How to reduce the stock for specific order status in WooCommerce

跟風遠走 提交于 2021-02-05 08:21:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!