Việc cập nhật giỏ hàng chúng ta có thể làm bằng nhiều cách. Bạn có thể làm một nút cập nhật ở dưới giỏ hàng tuy nhiên việc trãi nghiệm người dùng cũng không tốt được so với việc sử dụng ajax để load trạng thái của giỏ hàng.

Với việc sử dụng Ajax trong việc load các thông tin của giỏ hàng chúng ta cần quan tâm đến 2 điều chính

  1. Xoá một sản phẩm ra khỏi giỏ hàng
  2. Thay đổi số lượng của giỏ hàng. Việc thay đổi này sẽ bao gồm 2 chức năng chính là nhập số từ bàn phím và sử dụng nút tăng giảm (Cộng – trừ)

Code jQuery để thực hiện Ajax cho nút xoá khỏi giỏ hàng.

$(document).on('click', 'a.remove', function (e) {
    e.preventDefault();
    var product_id = $(this).attr("data-product_id"),
        cart_item_key = $(this).attr("data-cart_item_key"),
        product_container = $(this).parents('.mini_cart_item');

    // Add loader
    product_container.block({
        message: null,
        overlayCSS: {
            cursor: 'none'
        }
    });

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/wp-admin/admin-ajax.php',
        data: {
            action: "product_remove",
            product_id: product_id,
            cart_item_key: cart_item_key
        },
        success: function (response) {
            if (!response || response.error)
                return;

            var total = response.total;
            var totalPay = response.totalPay;
            $('#product_item_' + product_id).remove();
            $('span.totalAmount').html(total);
            $('.bold.t_red.totalPay').html(totalPay);
        }
    });
});

Code jQuery để thực hiện Ajax cho việc thay đổi số lượng sản phẩm cần mua.

function cartPlusMinusNumber() {
    const plus = $(".plus");
    const minus = $(".minus");
    const qty = $(".so-luong .quantity .qty");
    plus.click(function () {
        const product_container = $(this).parents('.mini_cart_item');
        const cart_item_key = $(this).prev().attr("name");
        let t = parseInt($(this).prev().val());
        let quality = t + 1;
        $(this).prev().attr('value', quality);
        $(this).prev().val(quality)
        updateItem(quality, product_container, cart_item_key);
    });
    minus.click(function () {
        const product_container = $(this).parents('.mini_cart_item');
        const cart_item_key = $(this).next().attr("name");
        let t = parseInt($(this).next().val());

        let quality = t - 1;
        if (quality >= 1) {
            $(this).next().attr('value', quality);
            $(this).next().val(quality)
            updateItem(quality, product_container, cart_item_key);
        } else {
            alert('Có phải bạn đang muốn xoá sản phẩm đã chọn?')
        }

    });
    qty.change(function () {
        const product_container = $(this).parents('.mini_cart_item');
        const cart_item_key = $(this).attr("name");
        let t = $(this).val();
        let quality = t;
        if (!$.isNumeric(quality)) {
            alert('Vui lòng nhập số!')
        } else if (quality == 0) {
            alert('Có phải bạn đang muốn xoá sản phẩm đã chọn?')
        } else if (quality < 1) {
            alert('Vui lòng nhập số lớn hơn 0')
        } else {
            $(this).val(quality)
            $(this).attr('value', quality);
            updateItem(quality, product_container, cart_item_key);
        }
    });
};
function updateItem(quality, product_container, cart_item_key) {
    product_container.block({
        message: null,
        overlayCSS: {
            cursor: 'none'
        },
        overlayCSS: {backgroundColor: '#375491'}
    });

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/wp-admin/admin-ajax.php',
        data: {
            action: "update_item_from_cart",
            quality: quality,
            cart_item_key: cart_item_key
        },
        success: function (response) {
            if (!response || response.error)
                return;

            var product_subtotal = response.product_subtotal;
            var total = response.total;
            var totalPay = response.totalPay;
            product_container.unblock();
            // Replace fragments
            product_container.find('.product-subtotal').html(product_subtotal);
            $('span.totalAmount').html(total);
            $('.bold.t_red.totalPay').html(totalPay);
        }
    });
};

Tiếp theo ta tạo Action để thực thi Ajax. Đặt đoạn code này trong function.php

Code để thực thi Ajax cho việc xoá sản phẩm khỏi của hàng

function warp_ajax_product_remove()
{
    global $woocommerce;
    // Get mini cart
    ob_start();

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] == $_POST['product_id'] && $cart_item_key == $_POST['cart_item_key']) {
            WC()->cart->remove_cart_item($cart_item_key);
        }
    }

    WC()->cart->calculate_totals();
    WC()->cart->maybe_set_cart_cookies();
    ob_get_clean();
    $total = $woocommerce->cart->get_cart_subtotal();
    $totalPay = $woocommerce->cart->get_cart_total();

    // Fragments and mini cart are returned
    $data = array(
        'total' => $total,
        'totalPay' => $totalPay,
        'cart_hash' => apply_filters('woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5(json_encode(WC()->cart->get_cart_for_session())) : '', WC()->cart->get_cart_for_session())
    );

    wp_send_json($data);

    die();
}

add_action('wp_ajax_product_remove', 'warp_ajax_product_remove');
add_action('wp_ajax_nopriv_product_remove', 'warp_ajax_product_remove');

Code để thực thi Ajax cho việc thay đổi số lượng sản phẩm:

function update_item_from_cart()
{
    global $woocommerce;
    $quantity = $_POST['quality'];

    // Get mini cart
    ob_start();

    foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
        if ($cart_item_key == $_POST['cart_item_key']) {
            WC()->cart->set_quantity($cart_item_key, $quantity, $refresh_totals = true);
            $_product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key);
            $get_product_subtotal = apply_filters('woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal($_product, $quantity), $cart_item, $cart_item_key);
        }
    }

    WC()->cart->calculate_totals();
    WC()->cart->maybe_set_cart_cookies();

    ob_get_clean();
    $total = $woocommerce->cart->get_cart_subtotal();
    $totalPay = $woocommerce->cart->get_cart_total();
    $data = array(
        'product_subtotal' => $get_product_subtotal,
        'total' => $total,
        'totalPay' => $totalPay,
        'cart_hash' => apply_filters('woocommerce_add_to_cart_hash', WC()->cart->get_cart_for_session() ? md5(json_encode(WC()->cart->get_cart_for_session())) : '', WC()->cart->get_cart_for_session())
    );

    wp_send_json($data);

    die();
}

add_action('wp_ajax_update_item_from_cart', 'update_item_from_cart');
add_action('wp_ajax_nopriv_update_item_from_cart', 'update_item_from_cart');

Cần lưu ý khi đặt hàm Ajax này là khi trả kết quả về bạn cần thay đổi các option của Ajax để dữ liệu có thể cập nhật sau khi thực thi thành công.