当订单中包含某个产品 ID 时,不要减少 woocommerce 中手动订单的库存

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

我希望能够创建手动订单,如果我添加具有特定 ID 的产品(在本例中为 796),那么它不应该减少订单的产品库存。

为此,我尝试使用我在网上找到的这个片段

add_filter( 'woocommerce_can_reduce_order_stock', function( $can_reduce, $order ) {

    $is_product_in_order = false;
    // get all order items
    $items = $order->get_items();
    if( $items ) {
        foreach ( $items as $item_id => $item ) {
            if( '796' == $item->get_product_id() ) {
                $is_product_in_order = true;
                break;
            }
        }
    }

    return $is_product_in_order ? false : $can_reduce;
}, 99, 2 );

如果我创建包含任何产品+ ID 为 796 的产品的订单并更改订单状态,它仍然会减少我的产品库存。
我尝试了另一种以元标记作为条件的方法,但它也不起作用。 谁能帮我解决这个问题吗?

php wordpress woocommerce hook-woocommerce
1个回答
0
投票

尝试以下(未经测试),它可以处理多个产品 ID (或变体 ID)

add_filter( 'woocommerce_can_reduce_order_stock', 'can_reduce_order_stock_exceptions', 9000, 2 );
function can_reduce_order_stock_exceptions( $can_reduce, $order ) {
    // Define your product ID(s) or variation ID(s) that will avoid stock reduction
    $targeted_ids = array( 796 );

    // Loop through order items
    foreach ( $order->get_items() as $item_id => $item ) {
        if ( in_array($item->get_product_id(), $targeted_ids) 
        || in_array($item->get_variation_id(), $targeted_ids) ) {
            $can_reduce = false;
            break;
        }
    }
    return $can_reduce;
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

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