我搜索并找到了许多关于如何更改运费的示例。基本上我想做同样的事情,但我想使用 3rd 方 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.
关于php - 在 Woocommerce 3 中以编程方式设置自定义运费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48786788/