Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce add a custom fee using ajax to cart totals on checkout page

I am trying make it when user changes the Shipping address select dropdown it dynamically add a fee to cart totals using ajax.I could able to to get the value but when select a another state it wont update the totals.

My ajax request:

jQuery(document).ready(function () {
    jQuery('#shipping_state').change(function () {
        var data = {
            action: 'woocommerce_custom_fee',
            security: wc_checkout_params.update_order_review_nonce,
            add_order_fee: 'state',
            post_data: jQuery('form.checkout').serialize()
        };
        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
                var result = '';
                result = jQuery.parseJSON(code);
                if (result.result === 'success') {

                    jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });
        return false;
    });
})
And in functions.php

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
global $woocommerce;
$destsuburb = $woocommerce->customer->get_shipping_state();

/*Then I use $destsuburb as a variable to API and get a shipping cost returning $shipping_cost*/

$woocommerce->cart->add_fee('Shipping and Handling:', $shipping_cost);
}

I am getting different Shipping cost according to the State,but its not changing the front end value through add_fee()

like image 843
Frank Susith Nirmal Fernando Avatar asked May 18 '15 07:05

Frank Susith Nirmal Fernando


People also ask

How do I add fees to WooCommerce checkout?

So in your WordPress dashboard, go to Plugins > Add new and search for Checkout Manager for WooCommerce. Click Install Now and then Activate to complete the setup. Now, go to WooCommerce > Checkout and open the Billing tab under it. You'll see several billing fields that you can enable or disable for the checkout.

How do I add a custom fee in WooCommerce?

This setting can be found under Woocommerce >> Settings >> Custom Fee. Once administrator saves the settings, then customers will have this dynamically defined fee to their order total.


2 Answers

Finally I found a solution using a session variable to store the Ajax value and add_fee()

My ajax request:

jQuery(document).ready(function () {

    jQuery('#State').click(function () {
        if (jQuery('#ship-to-different-address-checkbox').is(':checked')) {
            var state = jQuery('#shipping_state').val();
            var post_code = jQuery('#shipping_postcode').val();
        } else {
            var state = jQuery('#billing_state').val();
            var post_code = jQuery('#billing_postcode').val();

        }
        console.log(state + post_code);
        var data = {
            action: 'woocommerce_apply_state',
            security: wc_checkout_params.apply_state_nonce,
            state: state,
            post_code: post_code
        };

        jQuery.ajax({
            type: 'POST',
            url: wc_checkout_params.ajax_url,
            data: data,
            success: function (code) {
                console.log(code);
//                jQuery('.woocommerce-error, .woocommerce-message').remove();

                if (code === '0') {
//                    $form.before(code);
                    jQuery('body').trigger('update_checkout');
                }
            },
            dataType: 'html'
        });

        return false;
    });

});

And in functions.php

wp_enqueue_script('neemo_state', get_template_directory_uri() . '/js/state_test.js', array('jquery'));
wp_localize_script('neemo_state', 'wc_checkout_params', array('ajaxurl' => admin_url('admin-ajax.php')));

add_action('wp_ajax_woocommerce_apply_state', 'calculate', 10);
add_action('wp_ajax_nopriv_woocommerce_apply_state', 'calculate', 10);

function calculate() {
    if (isset($_POST['state'])) {
        global $woocommerce;
        $weight = WC()->cart->cart_contents_weight;
        $state = $_POST['state'];
        if ($state === "VIC") {
            $val = 1;
        } else {
            $val = 2;
        }
        session_start();
        $_SESSION['val'] = $val;
    }
}

add_action('woocommerce_cart_calculate_fees', 'woo_add_cart_fee');

function woo_add_cart_fee() {
    session_start();
    $extracost = $_SESSION['val'];
    WC()->cart->add_fee('Shipping & Handling:', $extracost);
}
like image 85
Frank Susith Nirmal Fernando Avatar answered Oct 19 '22 08:10

Frank Susith Nirmal Fernando


I had to code for accepting donation just before checkout and adding that donation amount to the cart as a fee - and to provide flexibility for user to change the donation amount any number of times before proceeding to pay. I used the following code and it worked so well. I had Donation amount and a donateNow button - <input type="button" id="donateNowBtn" value="Donate Now!"

code in function.php

add_action( 'wp_footer', 'woocommerce_click_donate_button', 80 );
function woocommerce_click_donate_button() {
    if (is_checkout()) {
    ?>
    <script type="text/javascript">
    jQuery( document ).ready(function( $ ) {
        $('#donateNowBtn').click(function(){
            jQuery('body').trigger('update_checkout');
        });
    });
    </script>
    <?php
    }
}


add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
function woo_add_cart_fee( $cart ){
        if ( ! $_POST || ( is_admin() && ! is_ajax() ) ) {
        return;
    }

    if ( isset( $_POST['post_data'] ) ) {
        parse_str( $_POST['post_data'], $post_data );
    } else {
        $post_data = $_POST; // fallback for final checkout (non-ajax)
    }

    if (isset($post_data['donation_amount'])) {
        $donation_amount = $post_data['donation_amount'] ;
        WC()->cart->add_fee( 'Donation Amount', $donation_amount );
    }

}
like image 25
Sreenivasa Hosamane Avatar answered Oct 19 '22 09:10

Sreenivasa Hosamane