How to implement a Dynamic Fee Based on Radio Button Selection in WooCommerce Checkout?

Mary-Kate Olsen
Release: 2024-10-20 17:55:31
Original
491 people have browsed it

How to implement a Dynamic Fee Based on Radio Button Selection in WooCommerce Checkout?

Dynamic Fee Based on Radio Button Selection in WooCommerce Checkout

To implement a dynamic fee based on radio button selection in the WooCommerce checkout, the following steps are recommended:

Customizing Radio Form Field

Update woocommerce_form_field_radio action to modify the radio button form field. This can improve the user experience by ensuring that labels are displayed inline.

<code class="php">add_action( 'woocommerce_form_field_radio', 'custom_form_field_radio', 20, 4 );
function custom_form_field_radio( $field, $key, $args, $value ) {
    if ( ! empty( $args['options'] ) &amp;&amp; is_checkout() ) {
        $field = str_replace( '</label><input ', '</label><br><input ', $field );
        $field = str_replace( '<label ', '<label style="display:inline;margin-left:8px;" ', $field );
    }
    return $field;
}
Copy after login

Adding Custom Packaging Fee

Attach to woocommerce_cart_calculate_fees to add a dynamic packaging fee. It checks for the selected packing option in the session and applies the appropriate fee.

<code class="php">add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 );
function add_packaging_fee( $cart ) {
    if ( is_admin() &amp;&amp; ! defined( 'DOING_AJAX' ) )
        return;

    $packing_fee = WC()->session->get( 'chosen_packing' ); // Dynamic packing fee
    $fee = $packing_fee === 'box' ? 9.00 : 3.00;
    $cart->add_fee( __( 'Packaging fee', 'woocommerce' ), $fee );
}</code>
Copy after login

Adding Radio Button Fields

Hook into woocommerce_review_order_after_shipping to add custom radio button fields for packaging selection.

<code class="php">add_action( 'woocommerce_review_order_after_shipping', 'checkout_shipping_form_packing_addition', 20 );
function checkout_shipping_form_packing_addition() {
    $domain = 'woocommerce';

    echo '<tr class="packing-select"><th>' . __('Packing options', $domain) . '</th><td>';

    $chosen   = WC()->session->get('chosen_packing');
    $chosen   = empty($chosen) ? WC()->checkout->get_value('radio_packing') : $chosen;
    $chosen   = empty($chosen) ? 'bag' : $chosen;

    // Add a custom checkbox field
    woocommerce_form_field( 'radio_packing', array(
        'type' => 'radio',
        'class' => array( 'form-row-wide packing' ),
        'options' => array(
            'bag' => __('In a bag '.wc_price(3.00), $domain),
            'box' => __('In a gift box '.wc_price(9.00), $domain),
        ),
        'default' => $chosen,
    ), $chosen );

    echo '</td></tr>';
}</code>
Copy after login

jQuery and Ajax Script

This script handles the Ajax functionality for updating fees on radio button selection.

<code class="php">add_action( 'wp_footer', 'checkout_shipping_packing_script' );
function checkout_shipping_packing_script() {
    if ( ! is_checkout() )
        return; // Only checkout page
    ?>
    <script type="text/javascript">
    jQuery( function($){
        $('form.checkout').on('change', 'input[name=radio_packing]', function(e){
            e.preventDefault();
            var p = $(this).val();
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'woo_get_ajax_data',
                    'packing': p,
                },
                success: function (result) {
                    $('body').trigger('update_checkout');
                    console.log('response: '+result); // just for testing | TO BE REMOVED
                },
                error: function(error){
                    console.log(error); // just for testing | TO BE REMOVED
                }
            });
        });
    });
    </script>
    <?php

}
Copy after login

PHP Ajax Function

This function processes the Ajax request, stores the selected packing option, and returns it.

<code class="php">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['packing']) ){
        $packing = sanitize_key( $_POST['packing'] );
        WC()->session->set('chosen_packing', $packing );
        echo json_encode( $packing );
    }
    die(); // Alway at the end (to avoid server error 500)
}</code>
Copy after login

This solution uses jQuery, Ajax, and custom WooCommerce functionality to dynamically update fees based on radio button selection, ensuring a smooth user experience during checkout.

The above is the detailed content of How to implement a Dynamic Fee Based on Radio Button Selection in WooCommerce Checkout?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!