Skip to content

Instantly share code, notes, and snippets.

@xadapter
Last active March 9, 2020 05:48
Show Gist options
  • Save xadapter/3410c5b1748fd9682eb3c3185d075e5f to your computer and use it in GitHub Desktop.
Save xadapter/3410c5b1748fd9682eb3c3185d075e5f to your computer and use it in GitHub Desktop.
Snippet to adjust shipping cost based on shipping class, destination city and price limit. It will adjust the shipping cost once for one shipping class irrespective of different products or quantity class and it doesn't depend on product quantity. PluginHive Plugins : https://www.pluginhive.com/product-category/woocommerce-plugin/. ELEX Plugins h…
/**
* Snippet to adjust shipping Cost based on Shipping Class, destination city and price limit. It will adjust the shipping cost once
* for one shipping class irrespective of different products or quantity class and it doesn't depend on product quantity.
* Created at : 17 May 2018
* Updated at : 17 May 2018
* PluginHive Plugins : https://www.pluginhive.com/product-category/woocommerce-plugin/
* Gist Link : https://gist.github.com/xadapter/3410c5b1748fd9682eb3c3185d075e5f
*/
add_filter( 'woocommerce_package_rates', 'xa_shipping_cost_adjustment_once_based_on_shipping_class', 10, 2 );
if( ! function_exists('xa_shipping_cost_adjustment_once_based_on_shipping_class') ) {
function xa_shipping_cost_adjustment_once_based_on_shipping_class( $shipping_costs, $package ){
$cost_adjustment = array(
'shipping_class_a' => 5, // Shipping class slug => cost_adjustment
'shipping_class_b' => -1,
);
$price_limit = 1000; // Price limit after which snippet will work
$destination = array( 'jeddah', 'xyz' ); // Provide City name in small letter like jeddah not Jeddah
$shipping_methods = array( 'flat_rate:3', 'flat_rate:4'); // Shipping methods to which adjustment has to be applied
$total_product_cost = null;
$shipping_class_cost = array();
foreach( $package['contents'] as $product ) {
$product_shipping_class = $product['data']->get_shipping_class();
if( isset($cost_adjustment[$product_shipping_class]) && ! isset($shipping_class_cost[$product_shipping_class]) ) {
$shipping_class_cost[$product_shipping_class] = $cost_adjustment[$product_shipping_class];
$total_product_cost += $product['line_total'];
}
elseif( isset($shipping_class_cost[$product_shipping_class]) ) {
$total_product_cost += $product['line_total'];
}
}
if( !empty($shipping_class_cost) && $total_product_cost > $price_limit && !empty($package['destination']['city']) && in_array( strtolower($package['destination']['city']), $destination) ) {
$total_cost_adjustment = array_sum($shipping_class_cost);
foreach( $shipping_methods as $shipping_method ) {
if( isset($shipping_costs[$shipping_method]) ) {
$shipping_costs[$shipping_method]->set_cost( (float) $shipping_costs[$shipping_method]->get_cost() + $total_cost_adjustment );
}
}
}
return $shipping_costs;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment