2

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?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
GeorgeP
  • 784
  • 10
  • 26

2 Answers2

3

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.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
0
    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>';    
Maulik patel
  • 2,546
  • 2
  • 20
  • 26