首页 > 解决方案 > 在 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; 
} 

标签: phpwordpresswoocommerceproductorders

解决方案


你已经很近了,但是在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 );

来自的wc_maybe_adjust_line_item_product_stock函数admin/wc-admin-functions.php包含以下过滤器挂钩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' );

推荐阅读