使Woocommerce中特定国家/地区的自定义计算运输方式成本

时间:2018-10-11 12:14:22

标签: php wordpress woocommerce country shipping-method

我正在寻找一种解决方案,使我可以更改每个运输区域的成本,因为我还需要以第二种货币(日本为€到日元)也具有取整值。我使用WC_Geolocation :: geolocate_ip()根据IP地址动态更改货币,但是我找不到改变运费区域成本的解决方案。一个例子来解释:

    $location = WC_Geolocation::geolocate_ip();
    $country = $location['country'];
    if($country === "JP"){
    //do some code to change every shipping zone cost with a custom value
    //(different for every shipping zone)
    } 

我希望我的解释很清楚。

1 个答案:

答案 0 :(得分:1)

已更新

  

您可能必须在常规运送设置中的“ 运输选项”标签下的“ 启用调试模式”,以禁用临时运送缓存。

以下代码将更改自定义计算中特定国家(此处为日本)的运输方式费用:

add_filter( 'woocommerce_package_rates', 'custom_shipping_rates_based_on_country', 20, 2 );
function custom_shipping_rates_based_on_country( $rates, $package ) {

    // ONLY for Japan
    if( $package['destination']['country'] !== 'JP' )
        return $rates;

    // Loop through shipping methods rates
    foreach( $rates as $rate_key => $rate ){

        // Excluding free shipping method
        if( $rate->method_id !== 'free_shipping') {

            // Get initial shipping rate cost
            $initial_cost = $rate->cost;

            ## ---- START ------------------------------------------- ##

            // Add your calculations and settings

            // Rounding decimal setting
            $rounding_decimals = 2;

            // Conversion rate
            $conversion_rate = 1.25;

            // New calculated cost
            $new_cost = $initial_cost * $conversion_rate;

            ## ----  END  ------------------------------------------- ##

            // Set the rate cost (rounded with 2 decimals)
            $rates[$rate_key]->cost = round( $new_cost, $rounding_decimals );

            // Taxes rate cost (if enabled)
            foreach ($rate->taxes as $key => $tax){
                if( $rate->taxes[$key] > 0 ){

                    // Calculating the tax rate unit
                    $tax_rate = $rate->taxes[$key] / $initial_cost;

                    // Calculating the new tax cost
                    $new_tax_cost = $tax_rate * $new_cost;

                    // set the new tax cost
                    $taxes[$key] = round( $new_tax_cost, $rounding_decimals );

                    $has_taxes = true;
                } else {
                    $has_taxes = false;
                }
            }
            if( $has_taxes )
                $rates[$rate_key]->taxes = $taxes;

        }
    }

    return $rates;
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。

  

别忘了启用回运缓存。