2017-10-16 102 views
2

將產品添加到我的woocommerce商店時,我設置重量(以kg爲單位)和尺寸(以cm爲單位)。如果[(高x長x寬)/ 5000]高於實際重量,那麼我希望用它來計算運費。尺寸定製Woocommerce產品重量計算

我想我可以使用過濾器來操縱$重量但沒有成功。這裏是我的代碼:

function woocommerce_product_get_weight_from_dimensions($weight) { 
    global $product; 
    $product = wc_get_product(id); 
    $prlength = $product->get_length(); 
    $prwidth = $product->get_width(); 
    $prheight = $product->get_height(); 
    $dimensions = $prlength * $prwidth * $prheight; 
    $dweight = $dimensions/5000; 
    if ($dweight > $weight) { 
     return $dweight; 
    } 
    return $weight; 
} 
add_filter('woocommerce_product_get_weight', 'woocommerce_product_get_weight_from_dimensions'); 

我在做什麼錯?

回答

2

沒有與$product = wc_get_product(id);作爲id應該是一個定義的變量$id而不是錯誤。

此外,WC_Product對象在您的掛鉤函數中已經是缺少的可用參數。

最後,我重新審視你的代碼使之更加緊湊:

add_filter('woocommerce_product_get_weight', 'custom_get_weight_from_dimensions', 10, 2); 
function custom_get_weight_from_dimensions($weight, $product) { 
    $dim_weight = $product->get_length() * $product->get_width() * $product->get_height()/5000; 
    return $dim_weight > $weight ? $dim_weight : $weight; 
} 

代碼放在您的活動子主題(或主題)的function.php文件或也以任何插件文件。

此代碼已經過測試並可正常工作。