wc_get_weight

Normalise weights, unify to kg then convert to wanted unit value.

Description

(float) wc_get_weight( (int|float) $weight, (string) $to_unit, (string) $from_unit = '' ); 

Usage: wc_get_weight(55, kg); wc_get_weight(55, kg, lbs,);

Returns (float)

Parameters (3)

0. $weight (int|float)
The weight.
1. $to_unit (string)
'g', kg,, lbs, oz
2. $from_unit — Optional. (string) => ''
g,, kg, lbs, oz

Usage

  1. if ( !function_exists( 'wc_get_weight' ) ) { 
  2. require_once ABSPATH . PLUGINDIR . 'woocommerce/includes/wc-formatting-functions.php'; 
  3.  
  4. // The weight. 
  5. $weight = null; 
  6.  
  7. // 'g', 'kg', 'lbs', 'oz' 
  8. $to_unit = ''; 
  9.  
  10. // (optional) 'g', 'kg', 'lbs', 'oz' 
  11. $from_unit = ''; 
  12.  
  13. // NOTICE! Understand what this does before running. 
  14. $result = wc_get_weight($weight, $to_unit, $from_unit); 
  15.  

Defined (1)

The function is defined in the following location(s).

/includes/wc-formatting-functions.php  
  1. function wc_get_weight( $weight, $to_unit, $from_unit = '' ) { 
  2. $weight = (float) $weight; 
  3. $to_unit = strtolower( $to_unit ); 
  4.  
  5. if ( empty( $from_unit ) ) { 
  6. $from_unit = strtolower( get_option( 'woocommerce_weight_unit' ) ); 
  7.  
  8. // Unify all units to kg first. 
  9. if ( $from_unit !== $to_unit ) { 
  10. switch ( $from_unit ) { 
  11. case 'g' : 
  12. $weight *= 0.001; 
  13. break; 
  14. case 'lbs' : 
  15. $weight *= 0.453592; 
  16. break; 
  17. case 'oz' : 
  18. $weight *= 0.0283495; 
  19. break; 
  20.  
  21. // Output desired unit. 
  22. switch ( $to_unit ) { 
  23. case 'g' : 
  24. $weight *= 1000; 
  25. break; 
  26. case 'lbs' : 
  27. $weight *= 2.20462; 
  28. break; 
  29. case 'oz' : 
  30. $weight *= 35.274; 
  31. break; 
  32.  
  33. return ( $weight < 0 ) ? 0 : $weight;