The cart can contain multiple products, so global $product
is not applicable here.
Instead, you can go through the cart and for each product for which the meta exists, add the value for this to the fee.
If the $fee is greater than 0, you can then apply it.
So you get:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialize
$fee = 0;
// Loop through cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Get meta
$ecofee = $cart_item['data']->get_meta( 'meta_product_grossecofee', true );
// NOT empty & variable is a number
if ( ! empty ( $ecofee ) && is_numeric( $ecofee ) ) {
// Addition
$fee += $ecofee;
}
}
// If greater than 0
if ( $fee > 0 ) {
// Add additional fee (total)
$cart->add_fee( __( 'Ecofee', 'woocommerce' ), $fee, false );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
Note: if you want to take into account the quantity per product:
Replace
// NOT empty & variable is a number
if ( ! empty ( $ecofee ) && is_numeric( $ecofee ) ) {
// Addition
$fee += $ecofee;
}
With
// NOT empty & variable is a number
if ( ! empty ( $ecofee ) && is_numeric( $ecofee ) ) {
// Get product quantity in cart
$quantity = $cart_item['quantity'];
// Addition
$fee += $ecofee * $quantity;
}