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.