Created
September 27, 2016 13:42
-
-
Save WooForce/07a66b3a2db8ac3251befea3a0d46a15 to your computer and use it in GitHub Desktop.
Group shipping rates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
add_filter('woocommerce_package_rates', 'wf_group_rates', 10, 2); | |
function wf_group_rates($rates, $package){ | |
$groups = array( | |
array( | |
'group_name'=> 'Mail Express', | |
'ids' => array('wf_shipping_usps:D_EXPRESS_MAIL','wf_shipping_usps:flat_rate_box_express'), | |
'operator' => 'min', | |
), | |
array( | |
'group_name'=> 'Standard Mail', | |
'ids' => array('wf_shipping_usps:D_FIRST_CLASS','wf_shipping_usps:D_STANDARD_POST'), | |
'operator' => 'min', | |
), | |
); | |
// Divide rates into groups | |
foreach($groups as $group_key => $group){ | |
$groups[$group_key]['rates'] = array(); | |
foreach($rates as $rate_key => $rate){ | |
if(in_array($rate->id, $group['ids'])){ | |
$groups[$group_key]['rates'][] = $rate; | |
unset($rates[$rate_key]); | |
} | |
} | |
} | |
foreach($groups as $group_key => $group){ | |
if(is_array($group['rates']) && count($group['rates'])){ | |
//Get lowest/highest rate and assign back with group name | |
$selected_rate = current(wf_sort_rate_by_cost($group['rates'], $group['operator'])); | |
$selected_rate->label = $group['group_name']; | |
$rates[$selected_rate->id] = $selected_rate; | |
} | |
} | |
return $rates; | |
} | |
function wf_sort_rate_by_cost($rates, $op = 'min'){ | |
usort($rates, function($rate1, $rate2) use ($op){ | |
if($rate1->cost == $rate2->cost){ | |
return 0; | |
} | |
switch($op){ | |
case 'min':default: | |
return ($rate1->cost < $rate2->cost) ? -1 : 1; | |
case 'max': | |
return ($rate1->cost > $rate2->cost) ? -1 : 1; | |
} | |
}); | |
return $rates; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment