drgzmmy6379 2018-02-14 12:02
浏览 167
已采纳

在Woocommerce 3中以编程方式设置自定义运费

I have searched and found a number of examples of how to change the shipping rates. Basically I am looking to do the same, but I want to use a 3rd party API.

I have set up a custom plugin with a functions.php and activated it. I think used something simple like this:

add_filter('woocommerce_package_rates','test_overwrite',10,2);
function test_overwrite($rates,$package) {

    echo "<h2>Can you see me</h2>";
    foreach ($rates as $rate) {
        //Set the price
        $rate->cost = 1000;
        //Set the TAX
        $rate->taxes[1] = 1000 * 0.2;
    }
    return $rates;
}

However when I run either the checkout, or basket, the filter does not seem to run because I cannot see the echo. I also tried print_r().

Am I missing something as to why I cannot run this filter ?

  • 写回答

1条回答 默认 最新

  • dos49618 2018-02-14 13:04
    关注

    As this is a filter and as the data is cached, you can't get any output with print_r().

    The correct way to make it work is the following:

    add_filter( 'woocommerce_package_rates', 'custom_shipping_costs', 20, 2 );
    function custom_shipping_costs( $rates, $package ) {
        // New shipping cost (can be calculated)
        $new_cost = 1000;
        $tax_rate = 0.2;
    
        foreach( $rates as $rate_key => $rate ){
            // Excluding free shipping methods
            if( $rate->method_id != 'free_shipping'){
    
                // Set rate cost
                $rates[$rate_key]->cost = $new_cost;
    
                // Set taxes rate cost (if enabled)
                $taxes = array();
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $rates[$rate_key]->taxes[$key] > 0 )
                        $taxes[$key] = $new_cost * $tax_rate;
                }
                $rates[$rate_key]->taxes = $taxes;
    
            }
        }
        return $rates;
    }
    

    Code goes in function.php file of your active child theme (active theme).

    Tested and works.

    Sometimes, you should may be need to refresh shipping methods:
    1) Empty cart first.
    2) Go to shipping Zones settings, then disable/save and re-enable/save the related shipping methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序