Reputation: 335
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
Upvotes: 4
Views: 3576
Reputation: 254373
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:
Upvotes: 4
Reputation: 101
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!
Upvotes: 0