且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WooCommerce使用ajax将自定义费用添加到结帐页面上的购物车总额

更新时间:2022-11-19 13:00:44

最后,我找到了一个使用会话变量存储Ajax值和add_fee()的解决方案

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

我的ajax请求:

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;
    });

});

在functions.php中

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);
}