php - 如何从国家/地区获得运费?
问题描述
我想这并不是真正的重复,我正在尝试计算运费,就像 woocommerce 每次客户下订单时都会这样做一样,“相关”问题似乎是在谈论为订单设置固定价格......
我正在尝试根据客户所在国家/地区在动态生成的订单(基本上是由wc_create_order()
.
我尝试在线搜索但没有任何有用的信息出现,我尝试使用calculate_shipping()
from 的方法WC_Abstract_Order
但它不起作用,我该怎么做才能计算出正确的运费?
是否有某个功能可以返回送货地址的运费/费率?
这是我尝试过的片段(我省略了添加项目的部分)
// Retrieving the shipping and billing address from the POST request
$shipping = json_decode(stripslashes($_POST['shipping']), true);
$products_ids = json_decode(stripslashes($_POST['products']), true);
// Adding them to the order
$order->set_address($shipping, 'shipping');
if (isset($_POST['billing'])){
$bill = json_decode(stripslashes($_POST['billing']), true);
$bill['email'] = $shipping['email'];
}
else {
$bill = $shipping;
}
$order->set_address($bill,'billing');
............
// Calculating the order total based on the items inside the cart
// (the calculate_shipping doesn't really do much)
$order->calculate_shipping();
$order->calculate_totals();
解决方案
因此,经过一番挣扎后,我找到了解决问题的方法,虽然不是一个干净的解决方案,但还不错。这是代码!
if( class_exists( 'WC_Shipping_Zones' ) ) {
$all_zones = WC_Shipping_Zones::get_zones();
$country_code = "CN"; //Just testing with a random country code, this should be your input
foreach ($all_zones as $key => $zona) {
$total_zones = $zona['zone_locations'];
// Getting all the zones and iterating them until you find one matching $country_code
foreach ($total_zonesa as $cur_country_code) {
if ($cur_country_code->code == $country_code){
// If you find a match you iterate over shipping_methods, if you don't have more than one flat_rate you should just break this like I did, otherwise you would have to struggle a little bit more with this
//The $flat_rate->cost is the thing you want to return
foreach ($zona['shipping_methods'] as $key => $value) {
$instance_id = $key;
$flat_rate = new WC_Shipping_Flat_Rate($instance_id);
print_r($flat_rate->cost);
break;
}
}
}
}
}
return false;
推荐阅读
- windows - 按文件扩展名批量搜索目录中的每个文件夹,并仅保留该扩展名的最大文件和所有其他文件类型
- azure - Azure 隔离计时器触发功能在部署到 Azure 后不起作用
- reactjs - 卡在 Edit src/App.js 并保存以在 heroku 重新加载
- ios - 当我们尝试删除服务器时,如何停止音频会话“outputVolume”观察者崩溃
- python - 尝试打印包含 int 和 str 的列表,但不打印整数
- google-apps-script - 为什么 Google 表格网络应用需要验证会导致“查看、编辑、创建和删除您的所有 Google 表格电子表格”
- jenkins - 从管道脚本解析 Jenkins 轮询日志
- apache-spark - 如何在窗口 10 (HADOOP_HOME) 的单个环境变量中设置两个路径
- android - Android studio 需要为 Mac Monterey 更新
- ios - 如何使用 PickerView 值作为 Timer 倒计时的起始编号