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.
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');
What am i doing wrong?
There is an error with $product = wc_get_product( id );
as id
should be a defined variable like $id
instead.
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;
}
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.