1
votes

I'm trying to get a website I'm working on to update the cart using AJAX instead of having to use the 'Update Cart' button in WooCommerce but I'm running into an issue and I don't know why?

Essentially I have the following function:

function kino_update_quantity() {
    $cart = WC()->cart;
    $value = $_POST['quantity'];
    $product = $_POST['product'];
    $cart->set_quantity($product, $value, true);
    echo json_encode($cart->total);
    wp_die();
}

I expect this function to take an product and quantity from the $_POST variables, set the quantity on this, then return a new total price.

However it's returning a total of 0, this is obviously incorrect. If I refresh the page however the totals have all been updated correctly. Also if I turn the boolean to false on the set_quantity call it returns the original total as expected.

I'm confused by this and any help on this issue would be of great use.

1

1 Answers

0
votes

Before 2.6.0. WooCommerce, released June 2016, updating cart totals was far more complex than what Original Poster provided and required creating a custom Ajax call.

Now WooCommerce cart page uses Ajax to update cart totals after clicking on Update cart button and you don't need to worry about backend, but simply hide Update cart button and then enqueue script which triggers this event on quantity change, using template redirect hook, dependency with jQuery and making sure that this script loads only on cart page. For this purpose you can use my free plugin, which also has some handy additional options:

Ajax Cart AutoUpdate for WooCommerce

To hide button with CSS, use class .button instead of tag, to keep it compatible with all WooCommerce versions:

.button[name='update_cart'] {
    display: none!important;
}

Or hide button with PHP head style:

add_action('wp_head', 'hide_update_cart_button', 20);
function hide_update_cart_button() {
    echo "<style>.button[name='update_cart']{ display: none!important;}</style>";
}

In this answer I show what js code in enqueued file should be:

How to update cart page product quantity automatically through AJAX