phpwordpresswoocommercecartfee

Add custom fee based on total weight in Woocommerce


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

So for example:

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.


Solution

  • 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.