简体   繁体   中英

Progressive quantity based shipping costs with a max cost in Woocommerce

(How) can I set a max_fee for flat fee shipping costs in WooCommerce?

Adding this to the costs field in the flat fee settings of a shipping method works:

(1 * [qty]) + [fee min_fee = "2,5"]

(ie shipping costs 2,5 per order + 1 Euro per product) -> at least 3,5 and increasing + 1 for each product).

However, I want to charge 3,50 at minimum (for 1 item) and 4,50 at max (for 2 or more items). Ie functionally this formula: (3,5 * [qty]) or [fee **max_fee** = "4,5"]

Is this possible? / What is the correct syntax to use? I cannot find this anywhere. I only found this reference ("add max_fee shortcode attribute for flat rate" / "allow max_fee in addition to min_fee in flat rate costs fields") which seems to indicate that a feature request for a max_fee for flat fees (other than for percentages) is implemented. But I can't get it to work.

You can't use available settings to charge a variable shipping cost as defined:

  • 3,50 for the first item
  • 4,50 for more than one item (2 or more)

So you will need to use the following custom hooked function:

add_filter('woocommerce_package_rates', 'custom_shipping_costs', 10, 2 );
function custom_shipping_costs( $rates, $package ){
    // Get cart items count
    $items_count = WC()->cart->get_cart_contents_count();

    // Your cost settings
    $new_cost = $items_count > 1 ? 4.5 : 3.5;

    // Loop through shipping methods rates
    foreach ( $rates as $rate_key => $rate ){
        $has_taxes = false;

        // Targeting "Flat rate" shipping methods
        if ( 'flat_rate' === $rate->method_id ) {
            $default_cost = $rates[$rate_key]->cost;

            $rates[$rate_key]->cost = $new_cost;

            $rate_conversion = $new_cost / $default_cost;

            // Taxes rate cost (if enabled)
            foreach ($rates[$rate_key]->taxes as $key => $tax){
                if( $tax > 0 ){
                    $taxes[$key] = $tax * $rate_conversion;
                    $has_taxes = true;
                }
            }
            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.

Once the code is saved, go in your flat rate settings and set the rate cost to 1.00 :

在此处输入图片说明

Now the shipping rate will change from 3.50 (for one item) to 4.50 (for more than one items)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM