plugins – Conditional shipping options if certain products are in the WooCommerce cart

My solution is based on this source snippet:

I created a new shipping class in WooCommerce called "no-free-shipping" (the slug is important since it must be replaced in the code if it has 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(
$shipping_services_to_hide = array(
$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;

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

return $available_shipping_methods;

My biggest problem was determining what the name of my "free shipping" option was, because there is no clearly defined slug in WooCommerce. To find this, I used the comment

echo var_dump($available_shipping_methods);

To print the name of the shipping option (in my case, "free_shipping: 1") that I included in the code to make it work.

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