Free Shipping Only for Free Sample Products in WooCommerce

This PHP code uses a shipping class named sample OR product id 636 to remove all shipping methods excluding free shipping. If you want to give away a free sample and apply free shipping to the sample, use this code in your child themes function file or custom code snippets plugin.

add_filter( 'woocommerce_package_rates', 'disable_flat_rate_for_specific_products', 100, 2 );
function disable_flat_rate_for_specific_products( $rates, $package ) {
    $disable_flat_rate = false;

    // Check if any product in the cart has the shipping class "sample" or is product ID 636
    foreach ( $package['contents'] as $item_id => $values ) {
        if ( has_term( 'sample', 'product_shipping_class', $values['product_id'] ) || $values['product_id'] == 636 ) {
            $disable_flat_rate = true;

    if ( $disable_flat_rate ) {
        // Loop through the shipping rates and remove flat rate
        foreach ( $rates as $rate_id => $rate ) {
            if ( $rate->method_id === 'flat_rate' ) {
                unset( $rates[$rate_id] );

    return $rates;

The code removes all shipping methods and applies free shipping only.

You can use multiple free shipping methods and target the one which doesn’t require any conditions.

Remove Local Pickup

The code will also include local pickup. To remove the local_pickup method as well, change the conditional to this :

if ( $rate->method_id === 'flat_rate' || $rate->method_id === 'local_pickup' ) {

Note : If testing, you may need to clear customer sessions and the template cache.


Make sure you swap out the shipping class slug sample and product id 636 to match your own.


Shows only the free shipping method for products assigned the sample shipping class.

Free Shipping for Free Samples