Simple HTML and JS Approach
Here’s the solution below:
HTML Code
<button id="hi-add-button" class="hi-add-button" data-button-add="true">ADD TO CART</button>
JQuery Code
jQuery(document).ready(function($) {
// Ajax Starts
// Manually replace using your actual product ID
const hi_products_group = [
{ product_id: 242, quantity: 2 }, // Product 1
{ product_id: 265, quantity: 1 }, // Product 2
// You can add more here..
];
let index = 0;
function addProductToCart() {
const getData = $('#hi-data-store').val();
const product = hi_products_group[index];
if (index >= hi_products_group.length) {
// Redirect to cart or update cart widget
window.location.href = wc_add_to_cart_params.cart_url;
return;
}
// increment
index++;
// Send the AJAX request to add the product to the cart.
$.ajax({
type: 'POST',
dataType: 'json',
url: wc_add_to_cart_params.ajax_url,
data: {
action: 'woocommerce_add_to_cart',
product_id: product.product_id,
quantity: product.quantity,
},
beforeSend: function(xhr) {
// Show loading spinner or disable button
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
$('#hi-add-button').text('PROCEED TO CART..');
},
success: function(response) {
if (index < hi_products_group.length) {
// pause for 600ms
setTimeout(addProductToCart, 600);
// Add the next product to the cart
addProductToCart();
} else {
// all products have been added, change button text
$('#hi-add-button').text('ADD TO CART');
}
},
error: function(xhr, status, error) {
// Handle error
console.log(error);
},
});
}
// '#hi-add-button' with the selector for the cart button.
$('#hi-add-button').click(function(e) {
e.preventDefault();
addProductToCart();
});
});
The above code has the following features