Conditional Shipping Options if Certain Products are in Cart WooCommerce

My solution is based off of this source snippet: https://www.xadapter.com/woocommerce-hide-shipping-methods-if-items-of-specific-shipping-class-is-not-in-cart/

I created a new Shipping class in WooCommerce called “no-free-shipping” (the slug is important as this must be replaced in the code if you have something different.)

In the functions.php file in your WordPress theme, add the following code:

add_filter('woocommerce_package_rates', 'xa_hide_shipping_method_when_shipping_class_product_is_in_cart', 10, 2);
function xa_hide_shipping_method_when_shipping_class_product_is_in_cart($available_shipping_methods, $package){
// Shipping class IDs that need the method removed

$shipping_classes = array(
    'no-free-shipping',         
);
$shipping_services_to_hide = array(
    'free_shipping:1'
);
$shipping_class_exists = false;
foreach(WC()->cart->cart_contents as $key => $values) {
    if (in_array($values['data']->get_shipping_class() , $shipping_classes)) {
        $shipping_class_exists = true;
        break;
    }
}

// Negation of shipping class exists.
if($shipping_class_exists) {
    foreach($shipping_services_to_hide as & $value) {
        //echo var_dump($available_shipping_methods);
        unset($available_shipping_methods[$value]);
    }
}

return $available_shipping_methods;
}

My biggest problem was determining what the name of my “free shipping” option was, because there isn’t a clearly defined slug in WooCommerce. To find this, I used the commented out

echo var_dump($available_shipping_methods);

To print out the name of the shipping option (in my case, “free_shipping:1”) which I included in the code to get it working.

Now, if any product with the “no-free-shipping” shipping class is added to the cart, the free shipping option is removed.