Posted on

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, WordCamp speaker and Internet marketer, Rodolfo Melogli has worked as a WooCommerce freelancer since 2011. He helps entrepreneurs and developers overcome their WooCommerce nightmares :) Rodolfo is the organiser of WordCamp Dublin, the Dublin WooCommerce Meetup, the Dublin Ecommerce Meetup and the Dublin WordPress Meetup. He enjoys interacting with people, travelling and chasing tennis & soccer balls. Of course, he loves pizza too.

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

  1. 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. This code works really great ! thank you.

    1. Awesome 🙂

  3. 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

  4. 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 🙂

  5. 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: http://businessbloomer.com/woocommerce-customization-hangout/. Hope this helps!

Questions? Feedback? Support? Leave your Comment Now!
If you're writing code, please wrap it between: [php] code_here [/php]

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.