Add custom fee based on total weight in Woocommerc

2019-08-23 15:49发布

In WooCommerce, I am trying to add a an additional shipping fee based on cart weight.

  • For the first 1500g the fee is 50$.
  • Above 1500g we add 10$ to this initial $50 by steps of 1000g

So for example:

  • if cart weight is 700g we add a fee of $50,
  • if cart weight is 2600g we add a fee of $70 ($50 + $10 +$10) …

I am stuck on the calculation:

function weight_add_cart_fee() {
    $feeaddtocart =  get_option('feeaddtocart');
    $customweight =  get_option('customweight');
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $cart_weight = WC()->cart->get_cart_contents_weight();

    if ($cart_weight <= 500 ) {
        $get_cart_total = $woocommerce->cart->get_cart_total(); 
        $newtotal = $get_cart_total + 50;
        WC()->cart->add_fee( __('Extra charge (weight): ', 'your_theme_slug'), $newtotal, false );
    }
}

How can I achieve this? Any help is appreciated.

1条回答
欢心
2楼-- · 2019-08-23 16:28

It can be done very easily with a custom function hooked in woocommerce_cart_calculate_fees action hook…

Updated:

  • Added conversion of cart weight in grams (instead of kilos by default)
  • Now for the first 1500g the fee is 50$ (instead of 500g)
  • Now above 1500g it add $10 by steps of 1000g.
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 30, 1 );
function shipping_weight_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Convert cart weight in grams
    $cart_weight = $cart->get_cart_contents_weight() * 1000;
    $fee = 50; // Starting Fee below 500g

    // Above 500g we add $10 to the initial fee by steps of 1000g
    if( $cart_weight > 1500 ){
        for( $i = 1500; $i < $cart_weight; $i += 1000 ){
            $fee += 10;
        }
    }
    // Setting the calculated fee based on weight
    $cart->add_fee( __( 'Weight shipping fee' ), $fee, false );
}

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

Tested and works.

查看更多
登录 后发表回答