Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce get current shipping zone

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 );
            }
        }
like image 420
ZecKa Avatar asked Dec 10 '22 11:12

ZecKa


1 Answers

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

}
like image 149
ZecKa Avatar answered Dec 13 '22 01:12

ZecKa