将产品添加到我的 woocommerce 商店时,我设置了重量(以千克为单位)和尺寸(以厘米为单位)。如果 [(高度 x 长度 x 宽度)/5000] 高于实际重量,那么我希望用它来计算运费。
我以为我可以使用过滤器来操纵 $weight 但没有成功。这是我的代码:
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 一样定义的变量
相反。
此外,WC_Product 对象已经是您的 Hook 函数中缺少的可用参数。
最后,我重新审视了您的代码,使其更加紧凑:
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 文件中或任何插件文件中。
此代码经过测试并且可以工作。
关于php - 根据尺寸计算自定义 Woocommerce 产品重量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46768483/