仅针对 Woocommerce 中的特定订单状态和付款方式减少库存 [英] Reduce stock only for specific order statuses and payment method in Woocommerce

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

问题描述

我正在为客户开发一些自定义 Woocommerce 功能.他们使用 BACS 支付网关来处理人工支付.

I'm working on a bit of custom Woocommerce functionality for a client. They use the BACS payment gateway to handle manual payments.

但是,网关目前为我们的需要过早地减少库存,即当订单处于暂停"状态时.我只想在订单标记为处理中"或完成"时减少库存(避免重复减少).

However, the gateway currently reduces the stock too early for our needs, i.e., when the order is "On Hold". I would like to ONLY reduce the stock when the order is marked "Processing" or "Complete" (avoiding duplicate reductions).

我已经设法防止库存在暂停"时自行减少,使用以下代码段:

I have manged to prevent the stock from reducing itself while "on hold" with the following snippet:

function wcs_do_not_reduce_onhold_stock( $reduce_stock, $order ) {
if ( $order->has_status( 'on-hold' ) ) {
$reduce_stock = false;
}
return $reduce_stock;
}
add_filter( 'woocommerce_can_reduce_order_stock', 'wcs_do_not_reduce_onhold_stock', 10, 2 );

我不太确定如何继续.虽然上述代码有效,但添加以下条件无效:

I'm not too sure how to proceed though. While the above code works, adding the following condition does not:

else if ( $order->has_status( 'processing' ) || $order->has_status( 'completed' ) ) {
$reduce_stock = true;
}

简而言之,我希望库存根据以下库存状态发生变化:

In short, I'd ideally like the stock to change depending on the following stock statuses:

  • 暂停 - 什么都不做
  • 已完成或正在处理 - 减少库存(仅一次)
  • 取消 - 增加库存(仅当最初减少时)

非常感谢任何帮助!

推荐答案

使用在 woocommerce_order_status_changed 中挂钩的自定义函数,您将能够定位正在处理"和已完成"' 订单状态更改会减少订单商品库存.

Using a custom function hooked in woocommerce_order_status_changed you will be able to target 'processing' and 'completed' order statuses change reducing order items stock.

我在您的函数中添加了一个条件,仅针对订单的BACS"支付网关进行定位.

I have added in your function a condition to target only "BACS" payment gateway on orders.

add_filter( 'woocommerce_can_reduce_order_stock', 'wcs_do_not_reduce_onhold_stock', 10, 2 );
function wcs_do_not_reduce_onhold_stock( $reduce_stock, $order ) {
    if ( $order->has_status( 'on-hold' ) && $order->get_payment_method() == 'bacs' ) {
        $reduce_stock = false;
    }
    return $reduce_stock;
}

add_action( 'woocommerce_order_status_changed', 'order_stock_reduction_based_on_status', 20, 4 );
function order_stock_reduction_based_on_status( $order_id, $old_status, $new_status, $order ){
    // Only for 'processing' and 'completed' order statuses change
    if ( $new_status == 'processing' || $new_status == 'completed' ){
    $stock_reduced = get_post_meta( $order_id, '_order_stock_reduced', true );
        if( empty($stock_reduced) && $order->get_payment_method() == 'bacs' ){
            wc_reduce_stock_levels($order_id);
        }
    }
}

代码位于活动子主题(或活动主题)的 function.php 文件中.

经过测试并有效

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

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