仅针对使用特定运输 class ID 的购物车商品禁用特定运输方式

Disable specific shipping method just for a cart item uses a specific shipping class ID

来自 答案代码,如果购物车中有另一件商品没有该运输 class ID 并且想要显示 flat_rate:2 再次根据产品运费 class?

您将改用以下内容:

add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 10, 2 );
function custom_hide_shipping_methods( $rates, $package ) {
    $found = $others = false; // Initializing
    $shipping_class_id  = 513; // <== ID OF YOUR SHIPPING_CLASS
    $shipping_rate_id   = 'flat_rate:2'; // <== Targeted shipping rate ID

    // Checking cart items for current package
    foreach( $package['contents'] as $key => $cart_item ) {
        $product = $cart_item['data']; // The WC_Product Object
        
        if( $product->get_shipping_class_id() == $shipping_class_id ) { 
            $found = true;
        } else {
            $others = true;
        }
    }
    
    if( $found && ! $others && isset($rates[$shipping_rate_id]) ) {
        unset($rates[$shipping_rate_id]); // Removing specific shipping method
    }

    return $rates;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。它应该有效。

Refresh the shipping caches:

  1. This code is already saved on your functions.php file.
  2. In a shipping zone settings, disable / save any shipping method, then enable back / save.

    You are done and you can test it.