wc_get_weight( int|float $weight, string $to_unit, string $from_unit = '' )
Normalise weights, unify to kg then convert to wanted unit value.
Description Description
Usage: wc_get_weight(55, ‘kg’); wc_get_weight(55, ‘kg’, ‘lbs’);
Parameters Parameters
- $weight
-
(Required) Weight.
- $to_unit
-
(Required) Unit to convert to. Options: 'g', 'kg', 'lbs', 'oz'.
- $from_unit
-
(Optional) Unit to convert from. Defaults to ''. Options: 'g', 'kg', 'lbs', 'oz'.
Default value: ''
Return Return
(float)
Source Source
File: includes/wc-formatting-functions.php
function wc_get_weight( $weight, $to_unit, $from_unit = '' ) {
$weight = (float) $weight;
$to_unit = strtolower( $to_unit );
if ( empty( $from_unit ) ) {
$from_unit = strtolower( get_option( 'woocommerce_weight_unit' ) );
}
// Unify all units to kg first.
if ( $from_unit !== $to_unit ) {
switch ( $from_unit ) {
case 'g':
$weight *= 0.001;
break;
case 'lbs':
$weight *= 0.453592;
break;
case 'oz':
$weight *= 0.0283495;
break;
}
// Output desired unit.
switch ( $to_unit ) {
case 'g':
$weight *= 1000;
break;
case 'lbs':
$weight *= 2.20462;
break;
case 'oz':
$weight *= 35.274;
break;
}
}
return ( $weight < 0 ) ? 0 : $weight;
}