Reduce WooCommerce Item Inventory By Attribute Value

ε祈祈猫儿з 提交于 2019-12-01 00:22:30

First error is in $item->get_attribute('pa_size'); as $item is an instance of WC_Order_Item_Product object and get_attribute() method doesn't exist for WC_Order_Item_Product Class.

Instead you need to get the an instance of the WC_Product object using get_product() method from WC_Order_Item_Product Class…

So your code should be:

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;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Note: This hooked function is going to reduce the stock quantity based on that new returned increased quantity value (in this case the real quantity multiplied by 15)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!