wc_get_weight()WC 1.0

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

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

No Hooks.

Return

float.

Usage

wc_get_weight( $weight, $to_unit, $from_unit );
$weight(int|float) (required)
Weight.
$to_unit(string) (required)
Unit to convert to. Options: 'g', 'kg', 'lbs', 'oz'.
$from_unit(string)
Unit to convert from. Options: 'g', 'kg', 'lbs', 'oz'.
Default: ''

Examples

0

#1 Convert 1000 grams to kilograms

wc_get_weight( 1000, 'kg', 'g' );
0

#2 Convert 1.6 kilograms to grams

wc_get_weight( 1.6, 'g', 'kg' );
-3

#3 Convert weight from "kg" to the default weight unit specified in woocommerce settings

wc_get_weight( $weight, get_option( 'woocommerce_weight_unit', 'g' ), 'kg' );

wc_get_weight() code WC 9.3.3

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;
}