4

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

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Mostafa AHmadi
  • 329
  • 4
  • 14
  • Have you tested my code? Is much better, low resource consumption and lightweight than a plugin. Thanks – LoicTheAztec Aug 16 '16 at 15:17
  • yes, i tested. I dont Know knowledge about code so i need your help: my theme name is "santa" and cart wight is "$woocommerce->cart->cart_contents_weight", how can i change this function to work? – Mostafa AHmadi Aug 16 '16 at 15:30

2 Answers2

4

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:

Community
  • 1
  • 1
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
0

I believe you could use this plugin to create an extra charge category. You may have to edit the plugin to make the % of cart fee a % of total weight fee but it shouldn't be too hard to figure out. I can't really edit the plugin for you unless I know where you are getting the weight from. You just have to edit the wc-extra-fee-option.php file and change line 133 so that $extra_fee_option_cost will be multiplied by the weight instead of $total. You can do this by putting the weight in a class and then calling the class on line 133. Alternatively you could make the weight a global variable and simply use that global variable in place of $total on line 133. Hope this helps!