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

问题描述

Disable specific shipping method if a cart item uses a specific shipping class ID 应答代码中,购物车中是否有另一个商品没有该发货类别ID,并且要根据产品的发货类别再次显示flat_rate:2

解决方法

您将改为使用以下内容:

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文件中。应该可以。

刷新发货缓存:

  1. 此代码已保存在您的functions.php文件中。
  2. 在运输区域设置中,禁用/保存任何运输方式,然后启用回退/保存。

    您已完成,您可以对其进行测试。