Black Friday & Cyber Monday SUPER SALE ALL WEEK:
Grab 40% OFF on plugins
Days
Hours
Minutes
Seconds

How to Add Cart Fees Based on Custom Radio Button in WooCommerce?

This post provides a quick guide on integrating fees via custom radio buttons on your WooCommerce cart page.

Where to Add Custom Code in WooCommerce?

It is advisable to add the code snippets to the functions.php file of your child theme. Access the file directly from Appearance->Theme File Editor->Locating the child theme’s functions.php from the right sidebar. You can also access it from your theme’s directory file. Insert the following code snippet in functions.php. The alternative & easy option is to install the Code Snippets plugin. You can then add the code as a new snippet via the plugin.

Solution: Adding Fees on WooCommerce Cart Page based on Custom Radio Button

Let’s consider an example of an online store selling a mobile phone that wants to add cart fees based on the custom radio button.

Below is the code snippet that applies options for adding an extended warranty fee of $29 or $49. Based on the selection, the warranty fee gets applied and added to the cart total.

add_action('woocommerce_cart_totals_before_order_total', 'ts_add_custom_radio_button_field');
function ts_add_custom_radio_button_field() {
    $radio_options = array(
        'option_1' => __('1 year($29)', 'text-domain'),
        'option_2' => __('2 years($49)', 'text-domain'),
	'option_3' => __('Not Needed', 'text-domain')
        // Add more options if needed
    );
    woocommerce_form_field('custom_radio_field', array(
        'type' => 'radio',
        'class' => array('form-row-wide'),
        'label' => __('Option for Extended Warranty cover', 'text-domain'),
        'required' => true,
        'options' => $radio_options,
    ), WC()->session->get('custom_radio_field'));
}
// Php Ajax (Receiving request and saving to WC session)
add_action( 'wp_ajax_woo_get_ajax_data', 'woo_get_ajax_data' );
add_action( 'wp_ajax_nopriv_woo_get_ajax_data', 'woo_get_ajax_data' );
function woo_get_ajax_data() {
    if ( isset($_POST['custom_radio_field']) ){
        $packing = sanitize_key( $_POST['custom_radio_field'] );
        WC()->session->set('custom_radio_field', $packing );
        echo json_encode( $packing );
    }
    die(); // Alway at the end (to avoid server error 500)
}
// Calculate and add extra fee based on radio button selection
add_action('woocommerce_cart_calculate_fees', 'add_custom_extra_fee', 20, 1);
function add_custom_extra_fee($cart) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return;
    }
    $radio_option = WC()->session->get( 'custom_radio_field' );
     if ($radio_option === 'option_1') {
        $extra_fee = 29.00; // Set your extra fee amount for Option 1
    } elseif ($radio_option === 'option_2') {
        $extra_fee = 49.00; // Set your extra fee amount for Option 2
    } else {
        $extra_fee = 0.00; // No fee for other options or if no option is selected
    }
    if ($extra_fee == 29) {
        $cart->add_fee(__('Extended Warranty(1 year)', 'text-domain'), $extra_fee, true,'standard');
    } elseif ($extra_fee == 49){
	$cart->add_fee(__('Extended Warranty(2 years)','text-domain'), $extra_fee, true,'standard');
	}
}
add_action( 'wp_footer', 'cart_update_qty_script' );
function cart_update_qty_script() {
    ?>
    <script>
    jQuery( 'div.woocommerce' ).on( 'change', '#custom_radio_field_field  input:radio', function () {
        var fee = jQuery(this).val();
        jQuery.ajax({
            type: 'POST',
            url: wc_cart_params.ajax_url,
            data: {
                'action': 'woo_get_ajax_data',
                'custom_radio_field': fee,
            },
            success: function (result) {
                jQuery( 'button[name="update_cart"]' ).removeAttr('disabled');
                jQuery( "[name='update_cart']" ).trigger( "click" );
            }
        });
    } );
    </script>
    <?php
}

Output:

In the below output, a Mobile phone is a product that is added to the cart, and if the customer chooses the extended warranty fee (2 years), then the warranty fee gets added to the cart total.

How to Add Cart Fees Based on Custom Radio Button in WooCommerce? - Tyche Softwares

In another scenario, if the customer chooses the “Not needed” option, then the extended warranty fee will not be added as shown below.

How to Add Cart Fees Based on Custom Radio Button in WooCommerce? - Tyche Softwares
How to Add Cart Fees Based on Custom Radio Button in WooCommerce? - Tyche Softwares

Easily Set Fees & Discounts For Payment Gateways

Finding it difficult to manage all payment gateway fees and adjusting your product pricing accordingly?

The Payment Gateway Based Fees & Discounts plugin is designed to set up fees & discounts for each of your payment modes and simplify your payment process.

Code Explanation:

  1. add_action(‘woocommerce_cart_totals_before_order_total’, ‘ts_add_custom_radio_button_field’): This line of code adds an action hook to the woocommerce_cart_totals section, specifically before the order total, and calls the function ts_add_custom_radio_button_field when this hook is triggered. This is where the custom radio button field will be added to the cart totals section.
  2. ts_add_custom_radio_button_field(): This function is responsible for rendering the custom radio button field on the cart totals section. It creates three radio options, ‘Extended Warranty Fee(1 year)’, Extended Warranty Fee(2 years), and ‘Not needed’, for customers to choose whether they want to add the extended warranty fee.
  3. woocommerce_form_field(): This function generates the HTML for the radio button field with the specified options and settings. It utilizes the $radio_options array defined in add_custom_radio_button_field() to populate the radio button choices.
  4. add_action( ‘wp_ajax_woo_get_ajax_data’, ‘woo_get_ajax_data’ ): This line sets up an AJAX action hook that listens for a POST request to the wp_ajax_woo_get_ajax_data endpoint. It calls the function woo_get_ajax_data to handle the AJAX request.
  5. woo_get_ajax_data(): This function is called when the AJAX request is made. It receives the selected value from the custom radio button field, sanitizes it, and stores it in the WooCommerce session as ‘custom_radio_field‘. It then echoes the value in JSON format back to the client.
  6. add_action(‘woocommerce_cart_calculate_fees’, ‘add_custom_extra_fee’, 20, 1): This line adds an action hook to the woocommerce_cart_calculate_fees event and calls the function add_custom_extra_fee when this hook is triggered. This function is responsible for calculating and adding the extra fee based on the selected radio option.
  7. add_custom_extra_fee($cart): This function calculates the extra fee based on the value stored in the WooCommerce session under ‘custom_radio_field’. If the value is ‘option_1’, it sets the extra fee to $29.00 or if the value is ‘option_2’, it sets the extra fee to $49. Otherwise, if it’s ‘option_3’ not set, the extra fee is set to $0.00. It then adds the fee to the cart using $cart->add_fee().
  8. add_action( ‘wp_footer’, ‘cart_update_qty_script’ ): This line adds an action hook to the footer section of the website and calls the function cart_update_qty_script when this hook is triggered. This function adds a JavaScript script to handle the change event of the custom radio button field and perform an AJAX request to update the cart.
  9. cart_update_qty_script(): This function is responsible for the JavaScript code that sends an AJAX request when the custom radio button field changes. It sends the selected value of the field to the wp_ajax_woo_get_ajax_data endpoint and triggers a click event on the “Update Cart” button to update the cart with the new extra fee.

Conclusion

Similar to the WooCommerce cart page, you can also add radio buttons on the WooCommerce checkout page & charge based on the options chosen. You can even add options to allow the order to be paid partially while only accepting a deposit payment at the time of the order being placed.

Please share your thoughts in the comments section regarding the usefulness of the code in implementing this specific feature.

Browse more in: Code Snippets, WooCommerce How Tos, WooCommerce Tutorials

Share It:

Subscribe
Notify of
1 Comment
Newest
Oldest
Inline Feedbacks
View all comments
Brijesh
9 months ago

Hi,
I was looking for this code snippet to add cart fess on radio button features for every long time.
This is really good article .

Thanks

1
0
Would love your thoughts, please comment.x
()
x