Home >Backend Development >PHP Tutorial >How to Dynamically Update Fees Based on User Selections in WooCommerce Checkout?
Dynamic Fee Update Based on Radio Button Selection in WooCommerce Checkout
When developing a WooCommerce plugin, it is often necessary to add dynamic fees to the checkout process. One common example is to offer different packaging options with varying costs, such as a plastic bag or a gift box. This article explores the best ways to achieve this and addresses security considerations.
Dynamic Fee Addition Using WC_Cart
<code class="php">function at87_add_custom_fees( WC_Cart $cart ){ $fees = 3; // fee amount $fees = isset($_GET['test']) ? $_GET['test'] : 3; $cart->add_fee( 'Emballagegebyr', intval($fees)); }</code>
This code adds a fee to the cart dynamically based on the value obtained from $_GET['test'], which could be modified using JavaScript or an Ajax request. However, it's important to note that using $_GET is not secure and should be used with caution.
AJAX-Based Solution
A more secure and dynamic approach is to use AJAX to update the fee. The following code provides a complete solution:
<code class="php">// Ajax script add_action( 'wp_footer', 'checkout_shipping_packing_script' ); function checkout_shipping_packing_script() { if ( ! is_checkout() ) return; ?> <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 } // Ajax request handler 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 code utilizes Ajax to send the selected packaging option to the server, which then saves it in the WooCommerce session. The checkout is updated dynamically without the need for a page refresh.
Conclusion
The Ajax-based approach provides a secure and efficient method to update fees dynamically based on user selections in the WooCommerce checkout process. It eliminates the need for $_GET and ensures a smooth and secure checkout experience.
The above is the detailed content of How to Dynamically Update Fees Based on User Selections in WooCommerce Checkout?. For more information, please follow other related articles on the PHP Chinese website!