根据尺寸自定义Woocommerce产品重量计算 [英] Custom Woocommerce product weight calculation from dimensions

查看:55
本文介绍了根据尺寸自定义Woocommerce产品重量计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在向woocommerce商店添加产品时,我会设置重量(以千克为单位)和尺寸(以厘米为单位).如果[(高度x长度x宽度)/5000]高于实际重量,那么我希望以此来计算运费.

When adding products to my woocommerce store I set weight (in kg) and dimensions (in cm). If [(Height x Length x Width) / 5000] is higher than actual weight then I want this to be used to calculate shipping.

我认为我可以使用过滤器来操纵$ weight,但是没有成功.这是我的代码:

I thought I could use a filter to manipulate $weight but with no success. Here is my code:

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');

我在做什么错了?

推荐答案

$ product = wc_get_product(id); 出现错误,因为 id 应该是定义的变量,例如 $ id .

There is an error with $product = wc_get_product( id ); as id should be a defined variable like $id instead.

此外,在挂钩函数中,WC_Product对象已经是缺少的可用参数.

Also the WC_Product object is already a missing available argument in your hooked function.

最后,我重新审视了您的代码,使其更加紧凑:

Finally, I have revisited your code making it more compact:

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文件中,也可能会出现在任何插件文件中.

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

此代码已经过测试并且可以正常工作.

This code is tested and works.

这篇关于根据尺寸自定义Woocommerce产品重量计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆