当 WooCommerce 提供免费送货服务时,将本地提货成本设置为零

问题描述 投票:0回答:1

我提供 45 欧元免费送货服务。我隐藏了其他运输方式,除了本地提货,当可以使用下面的代码免费时。

add_filter( 'woocommerce_package_rates', 'hide_shipping_except_local_when_free_is_available', 100 );
function hide_shipping_except_local_when_free_is_available($rates) {
    $free = $local = array();

    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
        } elseif ( 'local_pickup' === $rate->method_id ) {
            $local[ $rate_id ] = $rate;
        }
    }
    return ! empty( $free ) ? array_merge( $free, $local ) : $rates;
}

我的问题是,当购物车小计金额达到 45 欧元时,本地取货必须是免费的,因此当提供免费送货时,客户必须能够在 2 个免费选项(免费送货或免费本地取货)之间进行选择,或者选择付费运输选项。

我找不到方法。任何帮助将不胜感激。

php woocommerce cart minimum shipping-method
1个回答
1
投票

要在提供免费送货服务时还提供免费本地取货,请尝试使用以下代码替换(已注释):

add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 100, 2 );
function filter_woocommerce_package_rates( $rates, $package ) {
    // Initializing variables
    $free = array(); // Initializing variable

    // 1st Loop (free shipping): Loop through shipping rates for the current shipping package
    foreach ( $rates as $rate_key => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[$rate_key] = $rate;
            break;
        }
    }

    // 2nd Loop (local pickup): Loop through shipping rates for the current shipping package
    foreach ( $rates as $rate_key => $rate ) {
        // Set 'local_pickup' cost to zero when free shipping is available
        if ( 'local_pickup' === $rate->method_id && ! empty($free) ) {
            $taxes = array(); // Initializing variable

            // Loop through tax costs
            foreach ($rate->taxes as $key => $tax) {
                $taxes[$key] = 0; // Set tax cost to zero
            }
            $rate->cost = 0; // Set cost to zero
            $rate->taxes = $taxes; // Set back taxes costs array
            $free[$rate_key] = $rate;
            break; // Remove this, if there is more than 1 Local pickup option for a shipping Zone
        }
    }
    return ! empty($free) ? $free : $rates;
}

代码位于子主题的functions.php 文件中(或插件中)。应该可以。

重要提示:您必须清空购物车才能刷新运输方式缓存。

其他相关主题:

© www.soinside.com 2019 - 2024. All rights reserved.