How to Dynamically Update Fees Based on User Selections in WooCommerce Checkout?

Linda Hamilton
Release: 2024-10-20 18:04:31
Original
598 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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!