Can you please tell me how can I adapt this snippet (it disables the free shipping method for a certain product) to make it possible to disable the free shipping method when the cart has product/s which assigned a certain shipping class? (WooCommerce 4.2+)
Any help appreciated. Thanks.
function my_free_shipping( $is_available ) {
global $woocommerce;
// set the product ids that are ineligible
$ineligible = array( '4743' );
// get cart contents
$cart_items = $woocommerce->cart->get_cart();
// loop through the items looking for one in the ineligible array
foreach ( $cart_items as $key => $item ) {
if( in_array( $item['product_id'], $ineligible ) ) {
return false;
}
}
// nothing found return the default value
return $is_available;
}
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'my_free_shipping', 20 );
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try this:
function hide_shipping_methods( $available_shipping_methods, $package ) {
$shipping_classes = array( 'some-shipping-class-1', 'some-shipping-class-2' );
$excluded_methods = array( 'free_shipping' );
$shipping_class_exists = false;
foreach( $package['contents'] as $key => $value )
if ( in_array( $value['data']->get_shipping_class(), $shipping_classes ) ) {
$shipping_class_exists = true;
break;
}
if ( $shipping_class_exists ) {
$methods_to_exclude = array();
foreach( $available_shipping_methods as $method => $method_obj )
if ( in_array( $method_obj->method_id, $excluded_methods ) )
$methods_to_exclude[] = $method;
if ( $methods_to_exclude )
foreach ( $methods_to_exclude as $method )
unset( $available_shipping_methods[$method] );
}
return $available_shipping_methods;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_methods', 10, 2 );
Here $shipping_classes is array of the shipping classes slugs and $excluded_methods is array of excluded shipping methods if at least one of the products in the cart belongs to one of these shipping classes.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0