Ketan Lathiya Ketan Lathiya - 7 months ago 12
PHP Question

How to add custom shipping charge in woocommerce?

I want to add shipping charge using code in woocommerce. here is my reuirements.

If my shipping country is Australia then shipping charge is different and outside australia is also different.
now, if my shipping country is Australia and

1. if order value is < 100, then shipping charge is $100
2. if order value is > 100, then shipping charge is $0.


If my shipping country is outside Australia and

1. if order value is < 500, then shipping charge is $60
2. if order value is > 500 and < 1000, then shipping charge is $50
3. if order value is > 1000, then shipping charge is $0


So, how can I add custom shipping charge as per my above requirements when user change shipping country from checkout page.
I tried below code but it only works on order value, how can I add shipping country in below code in custom plugin.

class WC_Your_Shipping_Method extends WC_Shipping_Method {
public function calculate_shipping( $package ) {
global $woocommerce;
if($woocommerce->cart->subtotal > 5000) {
$cost = 30;
}else{
$cost = 3000;
}
}
$rate = array(
'id' => $this->id,
'label' => $this->title,
'cost' => $cost,
'calc_tax' => 'per_order'
);

// Register the rate
$this->add_rate( $rate );


}

Answer

Better to make custom plugin for shipping charge where you can use hook.
First extend 'WC_Your_Shipping_Method' class in your custom plugin and make function like this:

public function calculate_shipping( $package ) {
    session_start();
    global $woocommerce;

    $carttotal = $woocommerce->cart->subtotal;
    $country = $_POST['s_country']; //$package['destination']['country'];

    if($country == 'AU')
    {
        if($carttotal > 100){
            $cost = 5;
        }else{
            $cost = 10;//10.00;
        }
    }
    else
    {
        if($carttotal < 500){
            $cost = 60;//60.00;
        }else if($carttotal >= 500 && $carttotal <= 1000){
            $cost = 50;//50.00;
        }else if($carttotal > 1000){
            $cost = 0;
        }
    }

    $rate = array(
        'id' => $this->id,
        'label' => 'Shipping',
        'cost' => $cost,
        'calc_tax' => 'per_order'
    );

    // Register the rate
    $this->add_rate( $rate );
}