我想这并不是真正的重复,我试图以与woocommerce在客户下订单时执行的方式相同的方式计算运输价格,“相关”问题似乎在谈论为订单设置固定价格。 ..
我正在尝试根据动态生成的订单(基本上是由wc_create_order()
创建的订单)中客户所在的国家/地区来计算运费,但是似乎使用calculate_totals方法并没有太大作用。
我尝试在线搜索,但没有显示任何有用的信息,我尝试使用calculate_shipping()
中的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();
答案 0 :(得分:0)
因此,经过一番努力后,我找到了解决我的问题的方法,虽然不是一个干净的方法,但是仍然不错。这是代码!
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;