简体   繁体   中英

Update woocommerce cart dynamically

On my checkout page I added an input box for additional plastic bags for the products (the user can select how many plastic bags they want to add), and when the user changes the quantity there I would like to udpate the cart dynamically.

I'm using ajax on the theme script.js:

$(document).on('change', '#additionalBagsSize', function(event) {
    event.preventDefault()
    let data = {
        action : 'my_action',
        id : 1
    }
    $.post(ajaxurl, data, function(response) {
        // no response needed here
    });
})

And in wordpress functions.php:

add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
    WC()->cart->total = WC()->cart->total + 1000;
    echo WC()->cart->total;
}

I also tried to add a "fee":

function my_action_callback() {
    global $woocommerce;    
    $woocommerce->cart->add_fee( 'Surcharge', 500, true, '' );
    echo WC()->cart->total;
}

The adding of 1000 is just for testing purposes, and it doesn't update the cart unfortunately. Is there a way to programatically control the cart amount and update it in real time for the user to see?

Add below line in your ajax response which refresh the cart content

$(document).on('change', '#additionalBagsSize', function(event) {
    event.preventDefault()
    let data = {
        action : 'my_action',
        id : 1
    }
    $.post(ajaxurl, data, function(response) {
        jQuery(document.body).trigger('update_checkout'); //refresh the cart items and totals
    });
})

It seems that the total woocommerce cart amount is an array of added products (and not a string/integer) so it's impossible to just determine a new amount.

A better approach is to add the custom products you're interested in via the woocommerce plugin, and then use woocommerce functions to add or remove them from the cart.

To add:

WC()->cart->add_to_cart($id, $count);

To remove:

WC()->cart->remove_cart_item($cart_item_key);

Hope it can help someone

For adding cart fee, please check below code, in that you have to add some kind of session and then you will have to check for that session by this way you can add the fee

add_action( 'woocommerce_cart_calculate_fees', 'custom_function_checkout_fee', 20, 1 );

function custom_function_checkout_fee( $cart ) {
  if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

  $fee = WC()->session->get( 'add_fee' );
  if(isset($fee) && $fee != 0 && is_numeric($fee)){
    $cart->add_fee( __('Option Fee', 'woocommerce'), $fee );
  }
}



add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
    WC()->session->set('add_fee', 500 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM