No Free Shipping for Specific Product in WooCommerce

This PHP code enables you to exclude free shipping for a specific product by ID or shipping class.

Example : You may offer free shipping requiring a minimum order amount but want to exclude 1 or more products from free shipping. This code enables you to do that using the product id or shipping class.

add_filter( 'woocommerce_shipping_free_shipping_is_available', 'exclude_products_from_free_shipping', 10, 2 ); 
function exclude_products_from_free_shipping( $is_available, $package ) {
    // Define the shipping class slug that should not qualify for free shipping
    $excluded_shipping_class = 'no-free-shipping'; // Replace with your shipping class slug
    
    // Define the product IDs that should not qualify for free shipping
    $excluded_product_ids = array( 880 ); // Replace with your product IDs
    
    // Check if any product in the cart has the excluded shipping class or product ID
    foreach ( $package['contents'] as $item ) {
        $product = wc_get_product( $item['product_id'] );
        
        // Check if the product has the excluded shipping class
        if ( $product && $product->get_shipping_class() === $excluded_shipping_class ) {
            return false; // Product found with excluded shipping class, exclude from free shipping
        }
        
        // Check if the product has an excluded product ID
        if ( in_array( $item['product_id'], $excluded_product_ids ) ) {
            return false; // Product found with excluded product ID, exclude from free shipping
        }
    }
    
    return $is_available; // Default behavior
}

Paste the code at the end of your child themes functions file or custom code snippets plugins.

Conditional Free Shipping Settings

Swap out the shipping class slug and/or product id in the code to match your own to target specific products you want excluded from free shipping.

When testing, you may need to clear customer sessions and/or your template cache.

Testing code for shipping methods