


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'] ) && is_checkout() ) { $field = str_replace( '<input><br><input str_replace style="display:inline;margin-left:8px;" return><p><strong>Adding Custom Packaging Fee</strong></p> <p>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.</p> <pre class="brush:php;toolbar:false"><code class="php">add_action( 'woocommerce_cart_calculate_fees', 'add_packaging_fee', 20, 1 ); function add_packaging_fee( $cart ) { if ( is_admin() && ! 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>
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>
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 }
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>
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!

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Setting the httponly flag is crucial for session cookies because it can effectively prevent XSS attacks and protect user session information. Specifically, 1) the httponly flag prevents JavaScript from accessing cookies, 2) the flag can be set through setcookies and make_response in PHP and Flask, 3) Although it cannot be prevented from all attacks, it should be part of the overall security policy.

PHPsessionssolvetheproblemofmaintainingstateacrossmultipleHTTPrequestsbystoringdataontheserverandassociatingitwithauniquesessionID.1)Theystoredataserver-side,typicallyinfilesordatabases,anduseasessionIDstoredinacookietoretrievedata.2)Sessionsenhances

PHPsessionscanstorestrings,numbers,arrays,andobjects.1.Strings:textdatalikeusernames.2.Numbers:integersorfloatsforcounters.3.Arrays:listslikeshoppingcarts.4.Objects:complexstructuresthatareserialized.

TostartaPHPsession,usesession_start()atthescript'sbeginning.1)Placeitbeforeanyoutputtosetthesessioncookie.2)Usesessionsforuserdatalikeloginstatusorshoppingcarts.3)RegeneratesessionIDstopreventfixationattacks.4)Considerusingadatabaseforsessionstoragei

Session regeneration refers to generating a new session ID and invalidating the old ID when the user performs sensitive operations in case of session fixed attacks. The implementation steps include: 1. Detect sensitive operations, 2. Generate new session ID, 3. Destroy old session ID, 4. Update user-side session information.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version
God-level code editing software (SublimeText3)
