AJAX to add to cart multiple products woocommerce
I found some AJAX on here to add a product to cart through WC through a button click, and I am trying to modify it to be able to add multiple products with the single click. I am not super familiar with AJAX and not a PHP expert, though I do know a decent amount. I couldn’t really figure out a way to do it in one AJAX call, so my current attempt is to run multiple AJAX calls to add a single product.
The HTML (button):
<a data-ids="33507,33504," class="addToCartBtn">Add To Cart</a>
The JS:
<script>
(function ($) {
$('.addToCartBtn').click(function (e) {
e.preventDefault();
var dataHrefs = $(this).attr('data-ids');
var datHrefsArray = dataHrefs.split(",");
var filteredHrefs = datHrefsArray.filter(function (el) {
return el != "";
});
console.log(filteredHrefs); /* Successfully outputs the product IDs in an array */
filteredHrefs.forEach(function(item){
console.log(item); /* Successfully outputs each product ID as a string on a separate line */
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: item,
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data,
success: function (response) {
console.log('success');
},
});
return false;
});
});
})(jQuery);
</script>
The PHP (functions.php):
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = 1;
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Let me know if there’s anything else I need to include. Thanks for the help.
Leave an answer