Set custom shipping rates programmatically in Woocommerce 3

后端 未结 1 446
天命终不由人
天命终不由人 2020-12-18 14:54

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

相关标签:
1条回答
  • 2020-12-18 15:54

    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.

    0 讨论(0)
提交回复
热议问题