WooCommerce: Add Checkout Fees Based on Radio Button Choice (Ajax)

This is a great WooCommerce snippet (or plugin, if you wish to call it like that) for those who want to provide another layer of checkout fees. For example, you might need to display custom checkout radio buttons to pick packaging types, gift wrapping, specific services and whatever can increase your AOV (Average Order Value). Radio button selection must work with “Ajax” – which means as soon as the radio button is chosen, checkout must refresh in order to display the updated fees and totals.

Something similar (and also more complex, such as offering store products) is achieved by the WooCommerce Checkout Add-Ons Plugin sold on the official WooCommerce.com marketplace. But in this article, we take a look at custom coding – either way you’ve got something to play with!

Add Dynamic Fee to WooCommerce Checkout Based on Custom Radio Button Choice

PHP Snippet: Add Dynamic Fee Based on Custom Radio Buttons @ WooCommerce Checkout


/**
 * @snippet       Dynamic Radio Buttons Fees - WooCommerce Checkout
 * @how-to        Watch tutorial @ https://businessbloomer.com/?p=19055
 * @sourcecode    https://businessbloomer.com/?p=79316
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.5.1
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// Part 1 
// Display Radio Buttons
// Uses woocommerce_form_field()

add_action( 'woocommerce_review_order_before_payment', 'bbloomer_checkout_radio_choice' );

function bbloomer_checkout_radio_choice() {
	
	$chosen = WC()->session->get('radio_chosen');
	$chosen = empty( $chosen ) ? WC()->checkout->get_value('radio_choice') : $chosen;
	$chosen = empty( $chosen ) ? 'no_option' : $chosen;
		
	$args = array(
	'type' => 'radio',
	'class' => array( 'form-row-wide' ),
	'options' => array(
		'no_option' => 'No Option',
		'option_1' => 'Option 1 ($10)',
		'option_2' => 'Option 2 ($30)',
	),
	'default' => $chosen
	);
	
	echo '<div id="checkout-radio">';
	echo '<h3>Customize Your Order!</h3>';
	woocommerce_form_field( 'radio_choice', $args, $chosen );
	echo '</div>';
	
}

// Part 2 
// Add Fee and Calculate Total
// Based on session's "radio_chosen"

#2 Calculate New Total

add_action( 'woocommerce_cart_calculate_fees', 'bbloomer_checkout_radio_choice_fee', 20, 1 );

function bbloomer_checkout_radio_choice_fee( $cart ) {
 
  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
  
  $radio = WC()->session->get( 'radio_chosen' );
	
  if ( "option_1" == $radio ) {
	$fee = 10;
  } elseif ( "option_2" == $radio ) {
	$fee = 30;
  }
  
  $cart->add_fee( __('Option Fee', 'woocommerce'), $fee );
 
}

// Part 3 
// Refresh Checkout if Radio Changes
// Uses jQuery

add_action( 'wp_footer', 'bbloomer_checkout_radio_choice_refresh' );

function bbloomer_checkout_radio_choice_refresh() {
if ( ! is_checkout() ) return;
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('form.checkout').on('change', 'input[name=radio_choice]', function(e){
            e.preventDefault();
            var p = $(this).val();
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'woo_get_ajax_data',
                    'radio': p,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                }
            });
        });
    });
    </script>
    <?php
}

// Part 4 
// Add Radio Choice to Session
// Uses Ajax

add_action( 'wp_ajax_woo_get_ajax_data', 'bbloomer_checkout_radio_choice_set_session' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'bbloomer_checkout_radio_choice_set_session' );

function bbloomer_checkout_radio_choice_set_session() {
    if ( isset($_POST['radio']) ){
        $radio = sanitize_key( $_POST['radio'] );
        WC()->session->set('radio_chosen', $radio );
        echo json_encode( $radio );
    }
    die();
}

Where to add this code?

You can place PHP snippets at the bottom of your child theme functions.php file (before "?>" if you have it). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such delicate files - if you need more guidance, please take a look at my free WooCommerce Customization video tutorial.

Does this snippet still work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.

If you think this code saved you time & money, please join other Business Bloomer supporters and avail of 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free videos, tutorials and tips!

  • how-to-edit-woocommerce-with-php-snippets
  • woocommerce-hooks-add_action-list-visual
  • woocommerce-customize-single-product-page-PHP
  • woocommerce-customize-shop-page-PHP
  • woocommerce-advanced-customization
  • how-to-edit-woocommerce-cart
  • woocommerce-customize-checkout-page-PHP
  • woocommerce-email-customization
  • woocommerce-conditional-logic

Rodolfo Melogli

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as a WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza.

36 thoughts on “WooCommerce: Add Checkout Fees Based on Radio Button Choice (Ajax)

  1. Hi Rodolfo, really useful. Only one problem …every option that I insert is on a new line.
    So I have the in
    line1- choose point
    line2- option 1 text
    line3- choose point
    line4- option 2 text
    line5- choose point
    line6- option 3 text

    1. Hello Edoardo, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom CSS work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  2. Hello I’m trying to implement this on my site and it does the update via Ajax when I select an option, but the fee value is not being added.
    Does this happen to anyone else?

    1. Hi Luis, did you use the exact same code?

  3. Thank you! It works very well, BUT does not include VAT to the fee?

    I can’t seem to find a place in the code that defines if the fee is with or without VAT..

    Hope that you maybe can, Rodolfo 🙂

    /Tobias

    1. Hello Tobias, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  4. Hello Rodolfo,
    you are Very informative and easy to follow , is it possible to insert the radio buttons within the newly added “optional fee” slot of the checkout order review not below?also could you elaborate on why, when option_1 is set as the default the fee is not added i noticed another option must be selected and then option1 again in order to add the fee?

    1. Hi there! I’m sure you can move it wherever you like 🙂 In regard to the rest, yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  5. Hi, I have a question how can i change the code if instead of having fix fee to be %. like 3% of a total amount before the fee.

    1. Hello Valenitnos, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

    2. I can help you with this if you still need

  6. Hello! Do you know a solution for ‘discount if checkbox is selected’? meaning activating a checkbox which says: “I want a monthly Auto-Delivery”. This is pre-selected and the client gets directly 10% discount on his cart. If he ticks off the box, the discount gets removed and he pays full price. thanks 🙂

    1. Hello Riccardo, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  7. Hi, the snippet works but it does not add any of my fees.

    1. Works for me, sorry – you’ll need to troubleshoot it.

  8. Hi Rodolfo thanks very much for this snippet. one question, after I checkout and select an amount said $30. after I complete checkout. next time when I visit the website and add something to cart. the $30 fee is already in cart by default. it’s not the default no option. how can I reset to default no option on next time I visit the website with previous checkout with an option? Thank you.

    1. Hey Choutin, I guess the choice stays inside the session and you will need to clear it. However, I believe WooCommerce empties the session when an order is placed. Can you try with another theme and no plugins but WooCommerce?

    2. No, it still remain even after order placed. I use twenty nineteen theme and only woo commerce is enable. Please advise. Thank you

    3. Weird, it works for me and I use it on a client’s site. There must be something else, sorry

  9. Hi guys.

    I’m primarily a Laravel backend dev. But i got involved in a woocommerce project and your articles have been life savers.

    Just want to thankyou for the amount of invaluable content you put out.

    Much love from Kenya!

    1. Thank you so much!

  10. Hello Rodolfo, thank you very much for this fragment of php, but the question is how can I do this with a select?

    1. Hello Joshua, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  11. Hi Rodolfo, this is great! I’ve amended it to show the choice made in the order confirmation page int he woocommerce > orders section, but how can I add it to the confirmation email that is sent out?
    Thanks!

  12. Hello! If you have two options with the same price how do you know what the person has chosen?. In the woocommerce order information it only tells you the price, not what the person has selected. Thanks!

    1. Hello Patricia, thanks for your comment! In the “$cart->add_fee” part, you could possibly print the name of the option as well, so that you can know it for later. Hope this helps!

    2. Thats great! I did that thanks!

    3. Excellent 🙂

  13. This code works really great ! thank you.

    1. Awesome 🙂

  14. Thank you for your great work. The snippet has option 1 set as default. How can I change the default selection so that no option is selected

    1. Hello Jurgen, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  15. Once we choose the radio with $30. It should be updated in thank you page, isn’t it so?

    1. Hi there, thanks for your comment! Yes of course 🙂

  16. Hi Rodolfo thanks a lot for this php snippet ,but the question is if i had integrate an e-commerce theme in my woocommerce website where can i add this snippet and should i create a child theme ?

    1. Hello Sabrine, yes, I recommend to place this in your child theme’s functions.php file – if you need more guidance, please take a look at this video tutorial: https://businessbloomer.com/woocommerce-customization-hangout/. Hope this helps!

Questions? Feedback? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between: [php]code_here[/php]. Failure to complying with this (as well as going off topic) will result in comment deletion. You should expect a reply in about a week - this is a popular blog but I need to get paid work done first. Please consider joining #BloomerArmada to ask me 1-to-1 WooCommerce questions. Thank you :)

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.