在Woocommerce 3中以编程方式设置自定义运费 [英] Set custom shipping rates programmatically in Woocommerce 3
问题描述
我搜索并找到了许多有关更改运费的示例.基本上,我希望这样做,但是我想使用第三方API.
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.
我已经设置了一个带有functions.php的自定义插件并激活了它.我认为使用的是这样简单的东西:
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;
}
但是,当我运行结帐或购物篮时,过滤器似乎没有运行,因为我看不到echo
.我也尝试过print_r()
.
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 ?
推荐答案
由于这是一个筛选器,并且由于已缓存数据,因此print_r()
无法获得任何输出.
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;
}
代码进入您的活动子主题(活动主题)的function.php文件中.
Code goes in function.php file of your active child theme (active theme).
经过测试,可以正常工作.
Tested and works.
有时候,您可能需要刷新运输方式:
1)首先清空购物车.
2)进入运输区域"设置,然后禁用/保存并重新启用/保存相关的运输方法.
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.
这篇关于在Woocommerce 3中以编程方式设置自定义运费的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!