
[英]Custom Woocommerce product weight calculation from dimensions only for specific shipping methods
[英]Custom Woocommerce product weight calculation from dimensions
将产品添加到我的 woocommerce 商店时,我设置了重量(以公斤为单位)和尺寸(以厘米为单位)。 如果 [(Height x Length x Width) / 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 对象已经是您的挂钩函数中缺少的可用参数。
最后,我重新审视了您的代码,使其更加紧凑:
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 文件或任何插件文件中。
此代码经过测试并有效。
add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_show_product_dimensions_loop', 20 );
function bbloomer_show_product_dimensions_loop() {
global $product;
$dimensions = $product->get_dimensions();
if ( ! empty( $dimensions ) ) {
echo '<div class="dimensions"><b>Height:</b> ' . $product->get_height() . get_option( 'woocommerce_dimension_unit' );
echo '<br><b>Width:</b> ' . $product->get_width() . get_option( 'woocommerce_dimension_unit' );
echo '<br><b>Length:</b> ' . $product->get_length() . get_option( 'woocommerce_dimension_unit' );
echo '</div>';
}
}
in single page
short-description.php
global $product;
$dimensions = $product->get_dimensions();
echo '<div class="dimensions"><b>Height:</b> ' . $product->get_height() . get_option( 'woocommerce_dimension_unit' );
echo '<br><b>Width:</b> ' . $product->get_width() . get_option( 'woocommerce_dimension_unit' );
echo '<br><b>Length:</b> ' . $product->get_length() . get_option( 'woocommerce_dimension_unit' );
echo '</div>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.