在 Woocommerce 3 中以编程方式设置自定义运费
Set custom shipping rates programmatically in Woocommerce 3
我搜索并找到了许多关于如何更改运费的示例。基本上我想做同样的事情,但我想使用第 3 方 API。
我已经使用 functions.php 设置了一个自定义插件并激活了它。我认为使用这样简单的东西:
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()
。
我是否遗漏了为什么我不能 运行 这个过滤器?
由于这是一个过滤器并且数据已缓存,因此您无法使用 print_r()
获得任何输出。
使其工作的正确方法如下:
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 文件。
已测试并有效。
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.
我搜索并找到了许多关于如何更改运费的示例。基本上我想做同样的事情,但我想使用第 3 方 API。
我已经使用 functions.php 设置了一个自定义插件并激活了它。我认为使用这样简单的东西:
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()
。
我是否遗漏了为什么我不能 运行 这个过滤器?
由于这是一个过滤器并且数据已缓存,因此您无法使用 print_r()
获得任何输出。
使其工作的正确方法如下:
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 文件。
已测试并有效。
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.