Search code examples
phpwordpresswoocommerceattributescart

WooCommerce - Adding Extra fee to Cart based on total items weight


I need to add charge on product total weight and show it in cart.
I mean in cart, when adding an item, i will set an extra charge.

This charge should be calculate like this:

$extra_charge = $total_cart_weight * 0.15;

If it's possible, How can I achieve this?

Thanks


Solution

  • You can do it easily hooking this function to woocommerce_cart_calculate_fees hook, this way:

    function weight_add_cart_fee() {
    
        // Set here your percentage
        $percentage = 0.15;
    
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // Get weight of all items in the cart
        $cart_weight = WC()->cart->get_cart_contents_weight();
    
        // calculate the fee amount
        $fee = $cart_weight * $percentage;
    
        // If weight amount is not null, adds the fee calcualtion to cart
        if ( !empty( $cart_weight ) ) { 
            WC()->cart->add_fee( __('Extra charge (weight): ', 'your_theme_slug'), $fee, false );
        }
    }
    add_action( 'woocommerce_cart_calculate_fees','weight_add_cart_fee' );
    

    This code is tested and works. It goes on function.php file of your active child theme or theme.

    For tax options: see add_fee() method tax options depending on your global tax settings.

    Reference: