Woocommerce get current shipping zone

时光怂恿深爱的人放手 提交于 2019-12-23 11:58:29

问题


I create a custom shipping method. (https://docs.woocommerce.com/document/shipping-method-api/)

In the calculate_shipping function i want to set the price of my shipping method based on the shipping zone:

If shipping zone is 'Zone 1' set price to 15 else set price to 20

So i want to know, how can i get the current shipping zone ?

I already try to see this doc: https://docs.woocommerce.com/wc-apidocs/class-WC_Shipping_Zone.html Maybe i don't understand...

public function calculate_shipping( $package=Array()) {
            global $woocommerce;

            $cart_total=$woocommerce->cart->cart_contents_total;


            $current_hour=date('His');
            $start_hour='110000';
            $end_hour='210000';

            // CONDITIONAL CHECK 

                // OPEN HOUR
                if($current_hour >= $start_hour &&  $current_hour <= $end_hour){
                    $is_open=true;
                }else{
                    $is_open=false;
                }

                // price PER ZONE
                $zone=""; // need to know how to get zone name or zone id
                if($zone=='Zone 1' && $cart_total>='60'){
                    $min_order=true;
                    $cost = 6;
                }elseif($zone=='Zone 2' && $cart_total>='120'){
                    $min_order=true;
                    $cost = 8;
                }elseif($zone=='Zone 3' && $cart_total>='180'){
                    $min_order=true;
                    $cost = 9;
                }else{
                    $min_order=false;
                    $cost = 0;
                }

                if($is_open==true && $min_order==true){
                    $allowed=true;
                }else{
                    $allowed=false;
                }


            $rate = array(
                'id' => $this->id,
                'label' => 'Livraison Express T '.wc_get_shipping_zone().' T',
                'cost' => $cost,
            );

            // Register the rate
            if($allowed==true){
                $this->add_rate( $rate );
            }
        }

回答1:


I find a solution myself

Like that:

$shipping_zone = WC_Shipping_Zones::get_zone_matching_package( $package );

$zone=$shipping_zone->get_zone_name();

Complete function:

public function calculate_shipping( $package=Array()) {
    global $woocommerce;

    $shipping_zone = WC_Shipping_Zones::get_zone_matching_package( $package );

    $zone=$shipping_zone->get_zone_name();

    if($zone=='Zone 1'){
        $cost = 6;
    }else{
        $cost=12;
    } 
    $rate = array(
        'id' => $this->id,
        'label' => 'Delivery Name',
        'cost' => $cost,
    );

    $this->add_rate( $rate );

}


来源:https://stackoverflow.com/questions/43916432/woocommerce-get-current-shipping-zone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!