Skip to content

Instantly share code, notes, and snippets.

@andizzle
Created February 11, 2012 09:08
Show Gist options
  • Save andizzle/1798071 to your computer and use it in GitHub Desktop.
Save andizzle/1798071 to your computer and use it in GitHub Desktop.
WooCommerce product dimensions/weight units normaliser
<?php
/**
* For WooCommerce 1.4.2 and above
* Dimensions/weight Units Normaliser
* Author Andy Zhang
* Company: Hypnotic Zoo
* Company Url: hypnoticzoo.com
*/
/**
*
* Normalise dimensions, unify to cm then convert to wanted unit value
* $unit: 'in', 'm', 'cm', 'm'
* Usage: wooDimNormal(55, 'in');
*
*/
function wooDimNormal($dim, $unit) {
$wooDimUnit = strtolower($current_unit = get_option('woocommerce_dimension_unit'));
$unit = strtolower($unit);
if ($wooDimUnit !== $unit) {
//Unify all units to cm first
switch ($wooDimUnit) {
case 'in':
$dim *= 2.54;
break;
case 'm':
$dim *= 100;
break;
case 'mm':
$dim *= 0.1;
break;
}
//Output desired unit
switch ($unit) {
case 'in':
$dim *= 0.3937;
break;
case 'm':
$dim *= 0.01;
break;
case 'mm':
$dim *= 10;
break;
}
}
return $dim;
}
/**
*
* Normalise weight, unify to kg then convert to wanted to unit
* $unit: 'g', 'kg', 'lbs'
* Useage: wooWeightNormal(55,'lbs');
*
*/
function wooWeightNormal($weight, $unit) {
$wooWeightUnit = strtolower($current_unit = get_option('woocommerce_weight_unit'));
$unit = strtolower($unit);
if ($wooWeightUnit !== $unit) {
//Unify all units to kg first
switch ($wooWeightUnit) {
case 'g':
$weight *= 0.001;
break;
case 'lbs':
$weight *= 0.4535;
break;
}
//Output desired unit
switch ($unit) {
case 'g':
$weight *= 1000;
break;
case 'lbs':
$weight *= 2.204;
break;
}
}
return $weight;
}
?>
@sakis1979
Copy link

this is exactly what i need it. you put this code in function.php?

@slaurvick
Copy link

Where did you add this, and does it work?

@jorgept
Copy link

jorgept commented Oct 18, 2017

Hi, same question, in functions.php ???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment