Automatically Update WooCommerce Cart on Quantity Change

How to auto update cart when quantity changes in woocommerce; Woocommerce automatically update cart on quantity change; Plugin to update cart automatically when quantity changes; Automatic cart update on quantity change woocommerce; Update woocommerce cart automatically when changing quantity; Auto update cart quantity woocommerce; Woocommerce cart update without button click; Enable automatic cart update on quantity change; Woocommerce ajax update cart on quantity change; How to make woocommerce cart update automatically;

Explanation

Here's how you can make your WooCommerce cart update automatically when you change the quantity of a product, without needing to click an update button.

What This Does:

  • When you're on the cart page and change the quantity of a product, the cart will automatically update.
  • This is done using a bit of JavaScript magic (AJAX) that talks to your server behind the scenes.

How It Works:

  • A custom script is loaded on the cart page. This script listens for any changes in the quantity input fields.
  • When a change is detected, it sends the new quantity to the server using AJAX.
  • The server updates the cart with the new quantity and recalculates the totals.
  • Finally, the updated cart details are sent back to the page, refreshing the cart display without needing a full page reload.

Key Parts:

  • PHP Code: This part sets up the server-side handling. It listens for AJAX requests and updates the cart accordingly.
  • JavaScript Code: This part runs in your browser. It detects changes in the quantity fields and sends the necessary data to the server.

With this setup, your customers will enjoy a smoother shopping experience, as they won't need to manually update the cart every time they adjust quantities.

Code

<?php
/**
 * Automatically update WooCommerce cart when quantity changes.
 *
 * This snippet uses AJAX to update the cart totals without requiring a button click.
 * It hooks into the WooCommerce scripts and adds custom JavaScript to handle the AJAX request.
 */

// Enqueue custom script to handle AJAX cart update
function wp_dudecom_enqueue_ajax_cart_update_script() {
    if (is_cart()) {
        wp_enqueue_script('wp-dudecom-ajax-cart-update', get_template_directory_uri() . '/js/wp-dudecom-ajax-cart-update.js', array('jquery'), null, true);
        wp_localize_script('wp-dudecom-ajax-cart-update', 'wp_dudecom_ajax_cart', array(
            'ajax_url' => admin_url('admin-ajax.php'),
        ));
    }
}
add_action('wp_enqueue_scripts', 'wp_dudecom_enqueue_ajax_cart_update_script');

// Handle AJAX request to update cart
function wp_dudecom_ajax_update_cart() {
    WC()->cart->set_quantity($_POST['cart_item_key'], $_POST['quantity']);
    WC()->cart->calculate_totals();
    WC()->cart->maybe_set_cart_cookies();

    // Send updated cart fragments back to the front-end
    WC_AJAX::get_refreshed_fragments();
    wp_die();
}
add_action('wp_ajax_wp_dudecom_update_cart', 'wp_dudecom_ajax_update_cart');
add_action('wp_ajax_nopriv_wp_dudecom_update_cart', 'wp_dudecom_ajax_update_cart');

?>

// JavaScript file: wp-dudecom-ajax-cart-update.js
jQuery(function($) {
    $('body').on('change', '.woocommerce-cart-form input.qty', function() {
        var $this = $(this);
        var cart_item_key = $this.closest('tr').attr('data-cart_item_key');
        var quantity = $this.val();

        $.ajax({
            type: 'POST',
            url: wp_dudecom_ajax_cart.ajax_url,
            data: {
                action: 'wp_dudecom_update_cart',
                cart_item_key: cart_item_key,
                quantity: quantity
            },
            success: function(response) {
                // Update cart fragments
                if (response && response.fragments) {
                    $.each(response.fragments, function(key, value) {
                        $(key).replaceWith(value);
                    });
                }
            }
        });
    });
});

Instructions

File Location: Add the PHP code to your theme's functions.php file or a custom plugin file. The JavaScript code should be placed in a new file named wp-dudecom-ajax-cart-update.js within a js directory in your theme.

Prerequisites:

  • Ensure WooCommerce is installed and activated on your WordPress site.

Implementation Steps:

  1. Add PHP Code: Open your theme's functions.php file or a custom plugin file and paste the provided PHP code. This code enqueues the JavaScript file and handles the AJAX request to update the cart.
  2. Create JavaScript File: In your theme directory, create a folder named js if it doesn't exist. Inside this folder, create a new file named wp-dudecom-ajax-cart-update.js and paste the provided JavaScript code into this file.
  3. Verify File Paths: Ensure the path in the wp_enqueue_script function matches the location of your JavaScript file. It should be get_template_directory_uri() . '/js/wp-dudecom-ajax-cart-update.js'.
  4. Test the Functionality: Navigate to your WooCommerce cart page and change the quantity of a product. The cart should automatically update without needing to click an update button.

For further assistance or to explore more advanced functionalities, consider reaching out to wp-dude.com for professional WordPress support.