Conditionally customize WooCommerce cart grand total output based on a fee

1.4k views Asked by At

I try to do a quite simple thing but for me i don´t get it to work.

This is from the wc-cart-functions.php

        if ( ! empty( $tax_string_array ) ) {
            $taxable_address = WC()->customer->get_taxable_address();
            $estimated_text  = WC()->customer->is_customer_outside_base() && ! WC()->customer->has_calculated_shipping()
                ? sprintf( ' ' . __( 'estimated for %s', 'woocommerce' ), WC()->countries->estimated_for_prefix( $taxable_address[0] ) . WC()->countries->countries[ $taxable_address[0] ] )
                : '';
            $value .= '<small class="includes_tax">' . sprintf( __( '(includes %s)', 'woocommerce' ), implode( ', ', $tax_string_array ) . $estimated_text ) . '</small>';
        }
    }

    echo apply_filters( 'woocommerce_cart_totals_order_total_html', $value );
}

The $value should be different if any $fee is applied. But I only get 0.00 € Value from $fee Variable if I check for.

Could someone please help me with simply apply the Value of the FEE in a Variable and check in a simple if clause like:

if fee is applied ---> 1
else ---> 2

How can I do it?

1

There are 1 answers

2
LoicTheAztec On BEST ANSWER

As you can see you can use the woocommerce_cart_totals_order_total_html filter hook located in that wc-cart-functions.php core code, to alter the output of grand cart total:

add_filter( 'woocommerce_cart_totals_order_total_html', 'custom_cart_totals_order_total_html', 10, 1 );
function custom_cart_totals_order_total_html( $value ) {
    // Get the fee cart amount
    $fees_total = WC()->cart->fee_total;

    // HERE is the condition
    if( ! empty($fees_total) && $fees_total != 0 ){
        // Change/customize HERE $value (just for test)
        $value .= " <small>($fees_total)<small>";
    }

    // Always return $value
    return $value;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Never overide core files, as this is something prohibited, dangerous and not convenient for many reasons

You will need to customize the code in the condition for $value