【问题标题】:Reduce WooCommerce Item Inventory By Attribute Value按属性值减少 WooCommerce 项目库存
【发布时间】:2018-09-15 17:58:56
【问题描述】:

我有一个使用 Woocommerce“可变产品”的设置,其中唯一的变化是“尺寸”属性:15 克、100 克、250 克。我想要做的是使用该变化量传递给 Woo wc-stock-functions,这样当购买产品变化“15 克”时,总库存下降 15,而不是 1。

在 Woo 内部,有文件 wc-stock-functions (http://hookr.io/plugins/woocommerce/3.0.6/files/includes-wc-stock-functions/) - 这甚至提供了一个过滤器 woocommerce_order_item_quantity。我想用它来将库存数量乘以克数,并以这种方式减少库存。

我正在尝试这个:

// define the woocommerce_order_item_quantity callback 
function filter_woocommerce_order_item_quantity( $item_get_quantity, $order, 
$item ) { 
$original_quantity = $item_get_quantity; 
$item_quantity_grams = $item->get_attribute('pa_size');
// attribute value is "15 grams" - so remove all but the numerals
$item_quantity_grams = preg_replace('/[^0-9.]+/', '', $item_quantity_grams);
// multiply for new quantity
$item_get_quantity = ($item_quantity_grams * $original_quantity);

return $item_get_quantity; 
}; 

// add the filter 
add_filter( 'woocommerce_order_item_quantity', 
'filter_woocommerce_order_item_quantity', 10, 3 ); 

但我现在收到内部服务器错误作为响应。

有人知道我在上面的代码中做错了什么吗?感谢您的帮助。

【问题讨论】:

    标签: php wordpress woocommerce orders stock


    【解决方案1】:

    第一个错误出现在$item->get_attribute('pa_size'); 中,因为$itemWC_Order_Item_Product 对象的一个​​实例,而get_attribute() 方法对于WC_Order_Item_Product 类不存在。

    相反,您需要使用来自WC_Order_Item_Product 类的get_product() 方法获取WC_Product 对象的实例...

    所以你的代码应该是:

    add_filter( 'woocommerce_order_item_quantity', 'filter_order_item_quantity', 10, 3 ); 
    function filter_order_item_quantity( $quantity, $order, $item )  
    {
        $product   = $item->get_product();
        $term_name = $product->get_attribute('pa_size');
    
        // The 'pa_size' attribute value is "15 grams" And we keep only the numbers
        $quantity_grams = preg_replace('/[^0-9.]+/', '', $term_name);
    
        // Calculated new quantity
        if( is_numeric ( $quantity_grams ) && $quantity_grams != 0 )
            $quantity *= $quantity_grams;
    
        return $quantity;
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。

    注意:这个钩子函数将根据新返回的增加数量值减少库存数量(在本例中为实际数量乘以 15) p>

    【讨论】:

    • 哇,谢谢 LoicTheAztec,完美的代码解决了我的问题。这教会了我很多东西,一百万谢谢你的好先生!
    • 很棒的代码@LoicTheAztec!使用此代码,当我有 100 克库存时,它允许客户购买 120 克。不会显示缺货。
    • 是否可以更新此代码以检查订单是否已被标记为已取消并重新添加数量?
    • @ODApplications 由于您有 $order WC_Order 对象参数,您可以使用此 IF / ELSE 语句if ( $order->get_status() == 'cancelled' ) { // Do something } else { // Do something else }检查取消订单状态@
    猜你喜欢
    • 1970-01-01
    • 2017-11-27
    • 2015-10-07
    • 2013-12-29
    • 2017-07-06
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    相关资源
    最近更新 更多