Search code examples
wordpresswoocommerceproductcartfee

Add the values of product meta as fee in WooCommerce cart


In Italy there is a specific fee for the disposal of electronic products that must be paid during the purchase.

This "ecofee" is specific for each product.

I have set up a specific meta for each product called meta_product_grossecofee

I'd like to convert the value of this meta field in a fee on the cart.

This is the code I've tried, however without the desired result. Any advice?

add_action( 'woocommerce_cart_calculate_fees', 'ecofee_display' );
function ecofee_display(){
    global $product;
    $ecofee = $product->get_meta('meta_product_grossecofee');
    if ($ecofee) {

        WC()->cart->add_fee(__('Ecofee: ', 'txtdomain'), $ecofee);
    }
}

Solution

  • 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;
    }