在 WooCommerce 中从订单中删除产品时防止调整库存

Prevent adjust stock when removing product from an order in WooCommerce

我正在尝试找到一种方法来阻止产品在从订单中移除时重新入库。

这是当我们进入“订单”屏幕时,单击单个订单并从该订单中删除单个产品。作为标准,它会重新入库。

我一直在查看 wc_delete_order_item 函数,但似乎无法理解。

function wc_delete_order_item( $item_id ) { 

    if ( ! $item_id = absint( $item_id ) ) { 
        return false; 
    } 

    $data_store = WC_Data_Store::load( 'order-item' ); 

    do_action( 'woocommerce_before_delete_order_item', $item_id ); 

    $data_store->delete_order_item( $item_id ); 

    do_action( 'woocommerce_delete_order_item', $item_id ); 

    return true; 
} 

你很接近,但是在 wc_delete_order_item 之前我们可以在 includes/class-wc-ajax.php

中找到
// Before deleting the item, adjust any stock values already reduced.
    if ( $item->is_type( 'line_item' ) ) {
        $changed_stock = wc_maybe_adjust_line_item_product_stock( $item, 0 );

admin/wc-admin-functions.php 中的 wc_maybe_adjust_line_item_product_stock 函数包含以下过滤器挂钩 woocommerce_prevent_adjust_line_item_product_stock


因此,为了回答您的问题,您可以使用(可以通过其他参数进一步指定功能的地方:仅某些产品等...)

/**
 * Prevent adjust line item product stock.
 *
 * @since 3.7.1
 * @param bool $prevent If should prevent (false).
 * @param WC_Order_Item $item Item object.
 * @param int           $item_quantity Optional quantity to check against.
 */
function filter_woocommerce_prevent_adjust_line_item_product_stock ( $prevent, $item, $item_quantity ) {
    $prevent = true;

    return $prevent;
}
add_filter( 'woocommerce_prevent_adjust_line_item_product_stock', 'filter_woocommerce_prevent_adjust_line_item_product_stock', 10, 3 );

或者简而言之

add_filter( 'woocommerce_prevent_adjust_line_item_product_stock', '__return_true' );