Menu Close

Add custom fee based on total weight – Woocommerce

Image

Adding fee in woocommerce can be done very easily with a custom function hooked in woocommerce_cart_calculate_fees action hook.

PHP Snippet : Add custom fees based on cart items total weight

Add below code in function.php

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 );
} 
Posted in WooCommerce

You can also read...