防止 WooCommerce 在付款时减少库存

问题描述 投票:0回答:4

我正在开发一个通过 WooCommerce 处理车辆租赁的插件。默认的 WooCommerce 行为是在付款后立即减少订单中的商品库存。长话短说,我需要防止这种情况发生(我将实现一个自定义功能,仅在选定的租赁日期减少库存)。

在 WC_Order 类中,我发现了一个名为 payment_complete() 的函数(class-wc-order.php,第 1278 行)。

这个函数的内容如下:

if ( apply_filters( 'woocommerce_payment_complete_reduce_order_stock', true, $this->id ) )
            $this->reduce_order_stock(); // Payment is complete so reduce stock levels

在我看来,我只需要包含

add_filter( 'woocommerce_payment_complete_reduce_order_stock', '_return_false' );

在我的插件中,以防止付款时库存减少,但不幸的是这不起作用。我还尝试将 add_filter() 包装在一个在 init 时触发的函数中,但仍然没有运气。

非常感谢任何帮助。

wordpress woocommerce
4个回答
2
投票
function filter_woocommerce_can_reduce_order_stock( $true, $instance ) { 
return false; 
}; 
add_filter( 'woocommerce_can_reduce_order_stock','filter_woocommerce_can_reduce_order_stock', 10, 2 ); 

这帮助我解决了问题!


1
投票

这已经很旧了,但是如果您不想让 WooCommerce 管理库存,您可以告诉整个商店不要在选项中管理库存。或者,单独针对每个产品。

研究

reduce_order_stock()
类中的
WC_Abstract_Order
方法表明,在这些情况下库存不会减少。

/**
 * Reduce stock levels
 */
public function reduce_order_stock() {

    if ( 'yes' == get_option('woocommerce_manage_stock') && sizeof( $this->get_items() ) > 0 ) {

        // Reduce stock levels and do any other actions with products in the cart
        foreach ( $this->get_items() as $item ) {

            if ( $item['product_id'] > 0 ) {
                $_product = $this->get_product_from_item( $item );

                if ( $_product && $_product->exists() && $_product->managing_stock() ) {
                    $qty       = apply_filters( 'woocommerce_order_item_quantity', $item['qty'], $this, $item );
                    $new_stock = $_product->reduce_stock( $qty );

                    $this->add_order_note( sprintf( __( 'Item #%s stock reduced from %s to %s.', 'woocommerce' ), $item['product_id'], $new_stock + $qty, $new_stock) );
                    $this->send_stock_notifications( $_product, $new_stock, $item['qty'] );
                }

            }

        }

        do_action( 'woocommerce_reduce_order_stock', $this );

        $this->add_order_note( __( 'Order item stock reduced successfully.', 'woocommerce' ) );
    }
}

但是,OP 的观察是正确的,但存在拼写错误。

__return_false()
函数前面有2个下划线而不是1个,所以正确的代码是:

add_filter( 'woocommerce_payment_complete_reduce_order_stock', '__return_false' );

从那里我会将您的自定义库存减少函数添加到

woocommerce_payment_complete
挂钩。


0
投票

它不起作用,因为它应该是

__return_false
,而不是
_return_false
- 前缀有两个下划线。
__return_false()
只是 WordPress 在
wp-includes/functions.php
中定义的函数。


-1
投票

您应该使用 remove_filter 函数,而不是 add_filter。

© www.soinside.com 2019 - 2024. All rights reserved.