This is a great WooCommerce snippet (or plugin, if you wish to call it like that) for those who want to provide conditional checkout fees. For example, you might need to display custom checkout radio buttons to pick premium packaging types, gift wrapping options, specific services or 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 additional products) is achieved by the WooCommerce Checkout Add-Ons Plugin sold on the official WooCommerce.com marketplace. But in this case, we want to take a look at custom coding so you’ve got something to play with! Enjoy.

Add a 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 Fee @ WooCommerce Checkout
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// Part 1 
// Display Radio Buttons
 
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 ) ? '0' : $chosen;
       
   $args = array(
   'type' => 'radio',
   'class' => array( 'form-row-wide', 'update_totals_on_change' ),
   'options' => array(
      '0' => 'No Option',
      '10' => 'Option 1 ($10)',
      '30' => '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
  
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 ( $radio ) {
      $cart->add_fee( 'Option Fee', $radio );
   }
  
}
 
// Part 3 
// Add Radio Choice to Session
 
add_action( 'woocommerce_checkout_update_order_review', 'bbloomer_checkout_radio_choice_set_session' );
 
function bbloomer_checkout_radio_choice_set_session( $posted_data ) {
    parse_str( $posted_data, $output );
    if ( isset( $output['radio_choice'] ) ){
        WC()->session->set( 'radio_chosen', $output['radio_choice'] );
    }
}
Share:

Leave a Reply