I have the code following placed in functions.php
function shipping_weight_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$extraFee = 0;
$total_weight = 0;
// Loop though each cart item
foreach ( $cart->get_cart() as $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
// Get weight
$product_weight = $cart_item['data']->get_weight();
// NOT empty
if ( ! empty( $product_weight ) ) {
// Quantity
$product_quantity = $cart_item['quantity'];
// Add to total
$total_weight += $product_weight * $product_quantity;
}
}
if ( $total_weight > 10 ) {
$extraFee = 20;
}
}
add_action( 'woocommerce_cart_calculate_fees', 'shipping_weight_fee', 10, 1 );
How can I get $extraFee from first code snippet to work in following code:
I tried with global but it does not work. I believe the second code runs first but I am not sure.
add_filter( 'woocommerce_package_rates', 'custom_shipping_costs', 20, 2 );
function custom_shipping_costs( $rates, $package ) {
foreach( $rates as $rate_key => $rate ){
// Excluding free shipping methods
if( $rate->method_id != 'free_shipping'){
// Set rate cost
$rates[$rate_key]->cost += $extraFee + 3;
}
}
return $rates;
}
Please help, thank You!
2
Answers
If you don’t want to add a fee to the cart you can avoid using the
woocommerce_cart_calculate_fees
hook and create a single function with thewoocommerce_package_rates
hook (combining the two functions):The code has been tested and works. Add it to your active theme’s functions.php.
You can use the
WC_Cart
methodget_cart_contents_weight()
to get the cart total weight instead simplifying the code.This will work if cart is not split in multiple shipping packages (see the other code below).
The following code handle also the shipping taxes calculations:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Don’t forget to empty your cart to refresh shipping rates caches.
Handling multiple shipping packages
As cart items can be split into multiple shipping packages by some plugins or custom code, in that case, you will use the following code that handle also shipping taxes calculations:
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Don’t forget to empty your cart to refresh shipping rates caches.
Related: Filter "woocommerce_cart_contents_weight" not applied for shipping weight