Shipping cost discount based on a shipping classes in Woocommerce

一曲冷凌霜 提交于 2019-12-02 09:15:49

Update (Just about settings)

To add a discount only for "large" shipping class on "Flat rate" shipping method, You will have to:

  • Set the discounted price directly on your shipping method cost.
  • Calculation option "Per class: Charge shipping for each shipping class individually"

Like:


Original answer:

The following code will set the shipping cost of 50% for "Flat rate" shipping method, when a specific defined shipping method is found in cart items.

Testing: Temporary "Enable debug mode" in Shipping settings under Shipping options tab...

Shipping "Flat rate" settings: Your shipping classes costs should be defined.

In the code bellow define in each function your shipping class slug and your custom notice:

add_filter('woocommerce_package_rates', 'shipping_costs_discounted_based_on_shipping_class', 10, 2);
function shipping_costs_discounted_based_on_shipping_class( $rates, $package ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return $rates;

    // Your settings bellow
    $shipping_class = 'large'; // <=== Shipping class slug
    $percentage     = 50; //      <=== Discount percentage

    $discount_rate  = $percentage / 100;
    $is_found       = false;

    // Loop through cart items and checking for the specific defined shipping class
    foreach( $package['contents'] as $cart_item ) {
        if( $cart_item['data']->get_shipping_class() == $shipping_class )
            $is_found = true;
    }

    // Set shipping costs to 50% if shipping class is found
    if( $is_found ){
        foreach ( $rates as $rate_key => $rate ){
            $has_taxes = false;
            // Targeting "flat rate"
            if( 'flat_rate' === $rate->method_id  ){
                $rates[$rate_key]->cost = $rate->cost * $discount_rate;

                // Taxes rate cost (if enabled)
                foreach ($rates[$rate_key]->taxes as $key => $tax){
                    if( $tax > 0 ){
                        $has_taxes = true;
                        $taxes[$key] = $tax * $discount_rate;
                    }
                }
                if( $has_taxes )
                    $rates[$rate_key]->taxes = $taxes;
            }
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Don't forget to disable "debug mode" in shipping settings once this has been tested once.

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