针对特定订单状态更改禁用增加库存

时间:2021-05-12 15:23:40

标签: php wordpress woocommerce hook-woocommerce stock

当前当订单状态更改为 cancelled 时,产品的库存会增加。

我想在新状态为 cancelled 时禁用库存增加,但仅针对某些先前的订单状态(并非全部)

例如,当状态改变时:

  • processingcancelled:不增加库存
  • shippedcancelled:不增加库存
  • other-statuscancelled:增加库存
  • cancelledprocessing:减少库存

到目前为止,我已经尝试过:

我用 remove_action 函数尝试了 wc_increase_stock_levels,但它对我不起作用。我哪里做错了?

1 个答案:

答案 0 :(得分:1)

更新产品库存时无法获取之前的订单状态。这是因为 wc_maybe_increase_stock_levels 函数使用在钩子之前执行的 woocommerce_order_status_cancelled 钩子触发:

从这些钩子中,您可以获得以前和新的订单状态

您可以通过两个步骤解决此问题:

  1. 禁用取消状态的库存增加(无论之前的订单状态如何)
  2. 根据一个或多个先前的订单状态设置库存增加

如果您只想为状态从“other-status”(custom)更改为“cancelled”的订单启用库存增加,您可以使用以下代码:

<块引用>

other-status 替换为之前的订单状态 slug (没有 wc- 前缀)

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

代码已经过测试并且可以工作。将它添加到您的活动主题的functions.php。