Search code examples
phpwordpresswoocommercecarthook-woocommerce

How to add % to total sum but only in row and not actully upgrade total price


add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // The percentage
    $percent = 15; // 15%
    // The cart total
    $cart_total = $cart->cart_contents_total; 

    // The conditional Calculation
    $fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;

    if ( $fee != 0 ) 
        $cart->add_fee( __( "Extra", "woocommerce" ), $fee, false );
}

I'm looking for a code like this:

  • Add % to total cart, but I dont actully want it to update total cart price
  • I just want it to add extra row like it does now with "extra"

Example: you shop for 10 dollars

Total sum: 10 dollars Extra: 11,5 dollars

I still want total sum to be 10 dollars, but just to show them if they pay 15% "extra" I will send something extra.


Solution

  • Because this is shown 2x, use

    • woocommerce_review_order_before_order_total - checkout page
    • woocommerce_cart_totals_before_order_total - cart page
    function my_custom_fee_based_on_cart_total() {
        // optional
        //if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
    
        // The percentage
        $percent = 15; // 15%
        
        // Get cart total
        $cart_total = WC()->cart->get_cart_contents_total();
        
        // The conditional Calculation
        $fee = $cart_total >= 25 ? $cart_total * $percent / 100 : 0;
        
        echo '<tr class="my-class"><th>Extra</th><td>' . wc_price($fee) . '</td></tr>';
    }
    add_action( 'woocommerce_review_order_before_order_total', 'my_custom_fee_based_on_cart_total', 10, 0 );
    add_action( 'woocommerce_cart_totals_before_order_total', 'my_custom_fee_based_on_cart_total', 10, 0 );