如何减少 WooCommerce 中特定订单状态的库存 [英] How to reduce the stock for specific order status in WooCommerce

查看:66
本文介绍了如何减少 WooCommerce 中特定订单状态的库存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WooCommerce 上管理我的库存.

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?

推荐答案

on-hold"processing" 的库存已经减少>已完成" 订单状态,如您所见 for wc_maybe_reduce_stock_levels() 函数源代码,将函数挂接到以下钩子:

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

所以不要直接使用wc_reduce_stock_levels(),而是用wc_maybe_reduce_stock_levels()代替.

So don't use directly wc_reduce_stock_levels() and replace by wc_maybe_reduce_stock_levels().

但是在 WooCommerce 待处理 订单状态下,函数 wc_maybe_increase_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' );
});

代码位于活动子主题(或活动主题)的functions.php 文件中.它应该可以工作.

Code goes in functions.php file of the active child theme (or active theme). It should work.

请注意,woocommerce_order_status_{$status_transition_to} 是一个复合挂钩,可用于任何其他自定义订单状态.

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

代码位于活动子主题(或活动主题)的functions.php 文件中.它应该可以工作.

Code goes in functions.php file of the active child theme (or active theme). It should work.

这篇关于如何减少 WooCommerce 中特定订单状态的库存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆