为 Woocommerce 中的选定产品禁用特定的固定费率运输方式

Disable a specific of flat rate shipping method for a selected product in Woocommerce

在 Woocommerce 中,如何为特定的选定产品动态关闭特定的 "flat rate"?

例如
我有三种不同的统一费率选项。
可以使用选项 1、2 和 3 发送产品 A。
可以使用选项 1 和 2 发送产品 B。

感谢任何帮助。

这可以通过以下功能代码完成,您将在其中定义相关的产品 ID 和要禁用的送货方式 ID。

要找出正确的送货方式 ID,只需使用浏览器开发工具检查 "value" 参数下相应的 "flat rate" 单选按钮。

您可能需要在“送货选项”选项卡下的一般送货设置中"Enable debug mode"禁用送货缓存。

代码:

add_filter('woocommerce_package_rates', 'product_hide_shipping_method', 10, 2);
function product_hide_shipping_method( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    // HERE set your Shipping Method ID to be removed
    $shipping_method_id = 'flat_rate:12';

    // HERE set your targeted product ID
    $product_id = 37;

    $found = false;

    // Loop through cart items and checking for the specific product ID
    foreach( $package['contents'] as $cart_item ) {
        if( $cart_item['data']->get_id() == $product_id )
            $found = true;
    }

    if( $found ){
        // Loop through available shipping methods
        foreach ( $rates as $rate_key => $rate ){
            // Remove the specific shipping method
            if( $shipping_method_id === $rate->id  )
                unset($rates[$rate->id]);
        }
    }
    return $rates;
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。

Don't forget to re-enable "Enable debug mode" option in shipping settings.


对于多个产品 ID 的数组...替换行:

// HERE set your targeted product ID
$product_id = 37; 

与:

// Define your targeted product IDs
$product_ids = array(37, 39, 52, 58);

并替换行:

if( $cart_item['data']->get_id() == $product_id )

与:

if( in_array( $cart_item['data']->get_id(), $product_ids ) )

变量产品的最后一件事:如果您更喜欢处理父变量产品 ID 而不是产品变体 ID,请在代码中替换:

$cart_item['data']->get_id()

与:

$cart_item['product_id']