I am trying to apply complicated shipping rules in Woocommerce.
I have basic products which is:
| Spend | Shipping cost |
|---|---|
| less than 300 | 30$ |
| 300 or more | Free |
But I also have some large products and products with special delivery requirements
| product | Shipping Class | cost |
|---|---|---|
| large box | Truck with crane | 1000$ |
| large Box | Truck only | 200$ |
| Gazebo (Choice1: Delivery Only) | Delivery & Assebly | 200$ |
| Gazebo (Choice2: Delivery & Assembly) | Delivery & Assebly | 350$ |
Below is my shipping methods
For basic products everything is working well,
Also for large boxes its well as it shows in Standard shipping.
But when I add the (shipping with assembly) shipping method it still appear as choice even if no product with this class is in the cart.
I just need it to appear only when gazebo is in the cart
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_class_is_in_cart', 100, 2 );
function hide_shipping_when_class_is_in_cart( $rates, $package ) {
$free_shipping_method = 'free_shipping:13';
$shipping_classes = array('truck-crane','large-furniture','furniture-assembly');
$class_exists = false;
$cart_classes = array();
$shipping_methods = $shipping_zone->get_shipping_methods();
foreach( $package['contents'] as $cart_item )
$cart_item_class = $cart_item['data']->get_shipping_class();
if( in_array($cart_item_class , $shipping_classes ) ) {//Check if any shipping class exist
array_push($cart_classes,$cart_item_class); //push cart classes to array
$class_exists = true;
//break;
}
foreach($shipping_methods as $method){
$method_classes = $method->get_shipping_classes();
//Here i want to unset shipping methods which has no avaiable class in cart items
}
if( $class_exists )
unset( $rates[$free_shipping_method] );
return $rates;
}