禁用将特定订单状态(处理)的库存增加到取消订单

时间:2021-05-12 18:34:02

标签: php wordpress woocommerce stock

目前,订单取消会因订单状态变化而增加库存。

当我将订单状态更改为取消处理时,我想禁用增加库存,这可以增加库存水平。

示例: 处理 - 取消:不增加库存, 已发货 - 取消:不增加库存, 其他状态 - 取消:增加库存[默认功能], 取消 - 处理:减少库存[默认功能]

我试过了,

  1. 这将禁止为所有订单状态更改增加库存。
add_action( 'after_setup_theme', 'my_stop_cancelled_restock', 0 );
function my_stop_cancelled_restock() {
 remove_action('woocommerce_order_status_cancelled','wc_maybe_increase_stock_levels');    
}
  1. 移除操作对这个钩子不起作用
add_action( 'woocommerce_order_status_changed', 'grab_order_old_status', 10, 4 );
function grab_order_old_status( $order_id, $status_from, $status_to, $order ) {
 if($status_from == 'processing' && $status_to == 'cancelled'){
  remove_action('woocommerce_order_status_cancelled', 'wc_maybe_increase_stock_levels');
 }
}
  1. 以下代码用作第一个选项,不适用于特定的订单状态更改。此外,当我们将状态从取消更改为正在处理时,它会禁用减少功能
add_filter( 'woocommerce_can_restore_order_stock', 'ts_do_not_restock', 10, 2 );
function ts_do_not_restock( $true, $order ){
 $stat  = $order->get_status();
  if($stat == 'cancelled'){
   $note = 'order stat is '.$stat.' so we do not updated the item stock.';
    $order->add_order_note( $note ); // To be make sure what happened.
     return false;
    }
    else
    {
     return true;
   }
}
  1. 我还通过 woocommerce_order_status_changed 在 post meta 中保存了过去的订单状态,并在 woocommerce_can_restore_order_stock(第三个选项)中使用它,但它也不起作用。

remove_action 不起作用,否则我的工作会更容易。哪里也试过 wc_increase_stock_levels 这个,我哪里做错了?

1 个答案:

答案 0 :(得分:0)

这对我有用

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