首页 > 解决方案 > 如何从国家/地区获得运费?

问题描述

我想这并不是真正的重复,我正在尝试计算运费,就像 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();

标签: phpwordpresswoocommerce

解决方案


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

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;

推荐阅读