Skip to content

Instantly share code, notes, and snippets.

@xadapter xadapter/functions.php
Last active Sep 19, 2019

Embed
What would you like to do?
Snippet to hide normal shipping methods if any Freight Shipping Class in cart else Hide Freight Shipping methods if any normal WooCommerce Shipping Class product in cart. PluginHive Plugins - https://www.pluginhive.com/product/multiple-carrier-shipping-plugin-woocommerce/, https://www.pluginhive.com/product/woocommerce-ups-shipping-plugin-with-p…
/**
* Snippet to hide normal shipping methods based if any freight shipping class in cart else hide freight shipping method if any normal shipping class product in cart.
* Created at : 27 July 2018
* Updated at : 27 July 2018
* PluginHive Plugins : https://www.pluginhive.com/plugins/
* Gist Link : https://gist.github.com/xadapter/0504f1442d9c21d7014543bfc7589f78
*/
add_filter( 'woocommerce_package_rates', 'ph_hide_shipping_method_based_on_shipping_class', 10, 2 );
if( ! function_exists('ph_hide_shipping_method_based_on_shipping_class') ) {
function ph_hide_shipping_method_based_on_shipping_class( $shipping_rates, $package ) {
$hide_shipping_rates_based_on_shipping_class = array(
'normal_shipping_class' => array(
'shipping_class' => array('smart_phone'), // Normal Shipping classes
'shipping_method_to_hide' => array('flat_rate:1'), // Freight shipping method
),
'freight_shipping_class' => array(
'shipping_class' => array('shoe'), // Freight shipping classes
'shipping_method_to_hide' => array('free_shipping:2'), // Normal shipping method
),
);
$hide_freight_rates = $hide_normal_rates = false;
foreach( $package['contents'] as $line_item ) {
$line_item_shipping_class = $line_item['data']->get_shipping_class();
if( ! empty($line_item_shipping_class) ) {
if( in_array( $line_item_shipping_class, $hide_shipping_rates_based_on_shipping_class['freight_shipping_class']['shipping_class'] ) ) {
$hide_normal_rates = true;
break;
}
elseif( in_array( $line_item_shipping_class, $hide_shipping_rates_based_on_shipping_class['normal_shipping_class']['shipping_class'] ) ) {
$hide_freight_rates = true;
}
}
}
$shipping_methods_to_hide = array();
if( $hide_normal_rates ) {
$shipping_methods_to_hide = $hide_shipping_rates_based_on_shipping_class['freight_shipping_class']['shipping_method_to_hide'];
}
elseif( $hide_freight_rates ) {
$shipping_methods_to_hide = $hide_shipping_rates_based_on_shipping_class['normal_shipping_class']['shipping_method_to_hide'];
}
foreach( $shipping_rates as $key => $shipping_rate ) {
$id = $shipping_rate->get_id();
if( in_array( $id, $shipping_methods_to_hide) ) {
unset( $shipping_rates[$key] );
}
}
return $shipping_rates;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.