简体   繁体   中英

Custom woocommerce Cart AJAX Update

I am trying to AJAXify my Woocommerce cart but I am failing hard and I really can't find any help or documentation (I searched for days). So any help is desperately appreciated.

I tried two approaches:

  1. Custom AJAX Function When changing the quantity (on the cart page), a AJAX call is fired (-> admin-ajax.php) which triggers a function in my functions.php:

     function setQty() { global $woocommerce; WC()->cart->set_quantity( $_POST['itemKey'], $_POST['quantity'], true); echo json_encode(array('totalCount'=>WC()->cart->get_cart_contents_count(), 'total'=>$woocommerce->cart->total)); } 

The echoed JSON String contains the correct number of items in cart but the total amount is 0. When I reload the page the altered quantity is not saved. Same with

WC()->cart->add_to_cart($product_id, $quantity) or adding WC()->cart->calculate_totals()

I tried it this way so i can format the values I need to update my cart how i want. What am I missing here in order to get the cart update saved?

  1. The woocommerce built-in AJAX update function doesn't trigger, because I have a custom design and I think it needs a specific HTML-structure in order to work properly but i can't find any documentation or examples. Also I need the updated values (total amount, total count etc.) in a custom format. So far it just passes me "updated fragments" as predefined html code. How do i need to build the HTML code of my cart.php that the ajax update will work? And how do i alter the returning values?

Thank you very much in advance.

Is it a mini cart/counter you are trying to create or a full page to review/remove products?

If it is a mini-cart/cart counter you wanted, I've created a repo under https://github.com/samisonline/ajax_cart for you that has the basic functionality baked in. This may not be the exact format you're looking for, but it shows the woocommerce functionality at work, as well as the needed markup for AJAX to work!

I'm not sure what you'd like to update, but I guess you want to update the totals amount of products in the basket.

This example replaces and updates the HTML

Let's say you have a div where your total amount is in:

<div class="cart-totals"><?php echo WC()->cart->get_cart_contents_count(); ?></div>

Add this to your functions.php:

// Mini Cart update with AJAX
add_filter( 'woocommerce_add_to_cart_fragments', 'custom_cart_count_fragments', 10, 1 );
function custom_cart_count_fragments( $fragments ) {
    $fragments['div.cart-totals'] = '<div class="cart-totals">' . WC()->cart->get_cart_contents_count() . '</div>';
    return $fragments;
}

Note: You are replacing not adding

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