隐藏 Woocommerce 中某个产品类别的统一运费

Hide Flat Rate shipping exclusively for a product category in Woocommerce

这是这个问题的扩展:

为礼品卡产品使用了 Woo Smart Coupons 插件。这必须设置为变体,因为我们有多个层 select。 (这排除了虚拟产品) 礼品卡有自己的区分类别。我们设置了两个送货选项:统一费率 + 当地取件。将礼品卡发送到您的收件箱的运输选项非常愚蠢,因此我使用了上面 link 中的以下代码段:

add_filter( 'woocommerce_package_rates', 'conditional_hide_shipping_methods', 100, 2 );    
function conditional_hide_shipping_methods( $rates, $package ){

// Define/replace here your correct category slug (!)
$product_category = 'coupons-gift-cards';
$prod_cat = false;

foreach ( WC()->cart->get_cart() as $cart_item ) {
    $product_id = $cart_item['product_id'];
    if ( has_term( $product_category, 'product_cat', $product_id ) ){
        $prod_cat = true;
    }
}

$rates_arr = array();
if ( $prod_cat ) {
    foreach($rates as $key => $rate) {
        if ('free_shipping' === $rate->method_id || 'local_pickup' === $rate->method_id || 'local_delivery' === $rate->method_id) {
            $rates_arr[ $rate_id ] = $rate;
            break;
        }
    }
}
return !empty( $rates_arr ) ? $rates_arr : $rates;
}

非常有效...直到您添加不属于该类别的产品。如果有人决定他们想要礼品卡和普通产品,则需要恢复常规运输选项。

编辑:已检查的答案完美无缺!如果您想为上述情况更改项目的取货标签,使他们说 "Download" 而不是 "Pickup",则在检查哪些产品与类别匹配的 IF 语句后添加此行

foreach( $rates as $rate_key => $rate ) {
//change local_pickup:1 to your shipping method
    if ( 'local_pickup:1' == $rate_key){
//set the text for the label
        $rates[$rate_key]->label = __( 'Download', 'woocommerce' );
    }
}

以下是使其适用于独特且排他性产品类别的正确方法,如果此产品类别中没有其他产品剩余,它将专门隐藏统一费率:

add_filter( 'woocommerce_package_rates', 'hide_shipping_flat_rate_conditionaly', 90, 2 );
function hide_shipping_flat_rate_conditionaly( $rates, $package ){

    // HERE Define your product category (ID, slug or name or an array of values)
    $term   = 'coupons-gift-cards';
    $others = $found = false;

    foreach ( WC()->cart->get_cart() as $cart_item ) {
        $product_id = $cart_item['product_id'];
        if ( has_term( $term, 'product_cat', $cart_item['product_id'] ) )
            $found = true;
        else
            $others = true;
    }

    if ( $found && ! $others ) {
        foreach($rates as $rate_id => $rate) {
            if ('flat_rate' === $rate->method_id )
                unset($rates[ $rate_id ]);
        }
    }
    return $rates;
}

代码继续 function.php 您的活动子主题(或活动主题)的文件。

此代码已经过测试且功能齐全(如果您正确设置了送货区域,它会起作用)

You might need to refresh shipping cached data: disable, save and enable, save related shipping methods for the current shipping zone, in Woocommerce shipping settings.