Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}

like image 381
Ketan Lathiya Avatar asked Dec 27 '14 10:12

Ketan Lathiya


People also ask

How do I display shipping costs on WooCommerce product page?

Go to WooCommerce > Settings > Shipping and select the shipping zone you want to add Per-Product Shipping to. Then, click “Add shipping method” and add Per-Product as a shipping method. This is required for the Standalone Method so that Per-Product Shipping will be displayed as a shipping method at checkout.


1 Answers

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 );
}
like image 75
Manish Dakhara Avatar answered Sep 30 '22 14:09

Manish Dakhara