1

我正在建立一个包含运输的网站,但我有可以在所有运输区域收集的物品和可以在所有运输区域发送的物品。

所以我为所有区域设置了运输类。

我正在使用隐藏 woocommerce 中特定运输类别的运输方式答案代码,这正是我所需要的。

但是,除了放入每个 flat_rate id 之外,还有一种方法可以定位所有统一费率运输方式,因此当我添加其他统一费率运输设置时,它会为它工作,而无需我对代码进行更改。

我希望你明白我在追求什么。任何帮助表示赞赏。

4

1 回答 1

0

要将其用于所有“统一费率”运输方式和其他一些已定义的运输方式,您将使用以下内容:

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

    // HERE define your shipping class to find
    $class = 92;

    // HERE define the shipping methods you want to hide (others than "flat rate")
    $method_key_ids = array('local_pickup:3');

    $found = false;

    // Checking in cart items
    foreach( $package['contents'] as $cart_item ){
        // If we find the shipping class
        if( $cart_item['data']->get_shipping_class_id() == $class ){
            $found = true;
            break; // Stop the loop
        }
    }

    if( ! $found ) 
        return $rates;

    // Loop through shipping methods
    foreach( $rates as $rate_key => $rate ) {
        // Targetting "Flat rate" and other defined shipping mehods
        if( 'flat_rate' === $rate->method_id || in_array($rate->id, $method_key_ids) ) {
            unset($rates[$rate_key]);
        }
    }   

    return $rates;
}

代码位于您的活动子主题(或活动主题)的 function.php 文件中。测试和工作。

刷新运输缓存:( 必需)

  1. 此代码已保存在活动主题的 function.php 文件中。
  2. 购物车是空的
  3. 在运输区域设置中,禁用/保存任何运输方式,然后启用返回/保存。
于 2019-04-14T20:36:29.890 回答