【问题标题】:How to get shipping price from country?如何从国家/地区获得运费?
【发布时间】:2019-09-28 04:38:56
【问题描述】:

我想这并不是真正的重复,我正在尝试计算运费,就像 woocommerce 每次客户下订单时都会这样做一样,“相关”问题似乎是在谈论为订单设置固定价格。 ..

我正在尝试在动态生成的订单(基本上是由wc_create_order() 创建的订单)中根据客户所在的国家/地区计算运费,但使用calculate_totals 方法似乎没有多大作用。

我尝试在线搜索但没有任何有用的结果,我尝试使用 WC_Abstract_Order 中的 calculate_shipping() 方法但它不起作用,我该如何计算正确的运费?

是否有一个函数可以只返回送货地址的运费/费率?

这是我尝试过的sn-p(我省略了添加项目的部分)


    // 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();

【问题讨论】:

  • 当然,抱歉,我添加了一些 cmets 并更改了变量名称,希望现在更清楚
  • 如果您发现问题,请添加新答案。答案已解锁,因为您的问题已重新打开。祝你好运!

标签: php wordpress woocommerce


【解决方案1】:

所以,经过一番挣扎,我找到了解决问题的方法,虽然不是一个干净的解决方案,但还不错。这是代码!

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;

【讨论】:

    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2017-04-25
    • 2012-12-15
    • 1970-01-01
    • 1970-01-01
    • 2022-06-25
    相关资源
    最近更新 更多