Search code examples
phpwordpresswoocommercecartcheckout

Add a custom percentage fee based on Woocommerce session data


Below code will add a radio button to the woocommerce checkout form. If the buyer selects the radio button a fixed amount of money will be added to the cart Like 20 dollar $fee = 20;. What I need is instead of adding a fixed amount to add % of the total amount like 3%. The change I need to be done is in this section of the code:

add_action( 'woocommerce_cart_calculate_fees', 'custom_checkout_radio_choice_fee', 20, 1 );
function custom_checkout_radio_choice_fee( $cart ) {

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

    $radio = WC()->session->get( 'radio_chosen' );
    $disc=$order->get_total();

    if ( "option_1" == $radio ) {
        $fee = 20;
    } elseif ( "option_2" == $radio ) {
        $fee = 30;
    }

    $cart->add_fee( __('Option Fee', 'woocommerce'), $fee );
}

If the total amount before the user clicks the radio button is 200 dollar after clicking the radio button total become 206 dollar (add 3%).


Solution

  • The $order variable is not defined and the WC_Order object doesn't exist until the order is placed. Try the following instead:

    add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_radio_button_choice', 10, 1 );
    function custom_fee_based_on_radio_button_choice( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
            return;
    
        $radio = WC()->session->get( 'radio_chosen' );
    
        if ( "option_1" == $radio ) {
            $percent = 20;
        } elseif ( "option_2" == $radio ) {
            $percent = 30;
        }
    
        if( isset($percent) ) {
            $fee = $cart->get_subtotal() * $percent / 100; // Calculation
            $cart->add_fee( __('Option Fee', 'woocommerce'). " ($percent%)", $fee );    
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). tested and works.