0

✅ Hides usps_simple:GROUND_ADVANTAGE when product ID 2133 is in the cart.
✅ Shows only free shipping when all products in the cart belong to shipping class 61.
✅ Hides free shipping if there are mixed products (both free and non-free shipping items).
✅ Ensures free shipping stays hidden if it’s not available.

add_filter( 'woocommerce_package_rates', 'c2code_control_shipping_methods', 9999, 2 );
function c2code_control_shipping_methods( $rates, $package ) {
    $shipping_class_target = 61; // Target shipping class ID
    $restricted_product_id = 2133; // Product ID to check
    $restricted_shipping_method = 'usps_simple:GROUND_ADVANTAGE'; // Shipping method to hide
     $free_shipping_key = '';
    $has_target_class = false;
    $has_other_class = false;
    $has_restricted_product = false;
     // Check all products in the cart
    foreach ( WC()->cart->get_cart_contents() as $values ) {
        $product_id = $values['product_id'];
        $product_shipping_class = $values['data']->get_shipping_class_id();
         if ( $product_id == $restricted_product_id ) {
            $has_restricted_product = true;
        }
         if ( $product_shipping_class == $shipping_class_target ) {
            $has_target_class = true;
        } else {
            $has_other_class = true;
        }
         // If both types are found, no need to check further
        if ( $has_target_class && $has_other_class ) {
            break;
        }
    }
     // Find free shipping method key
    foreach ( $rates as $key => $rate ) {
        if ( strpos( $key, 'free_shipping' ) !== false ) {
            $free_shipping_key = $key;
        }
    }
     // Hide restricted shipping method if product ID 2133 is in cart
    if ( $has_restricted_product && isset( $rates[$restricted_shipping_method] ) ) {
        unset( $rates[$restricted_shipping_method] );
    }
     // Show only free shipping if all products are from the target shipping class
    if ( $has_target_class && !$has_other_class && $free_shipping_key ) {
        return array( $free_shipping_key => $rates[$free_shipping_key] );
    } 
     // Hide free shipping if mixed products exist
    if ( $has_other_class && $free_shipping_key ) {
        unset( $rates[$free_shipping_key] );
    }
     return $rates;
}

Jagdish Sarma Asked question March 6, 2025
Add a Comment