I use latest version of Wordpress and Woocommerce. I have some JavaScript that loops over DOM elements of class .selectable and grabs the product_id attribute from the ones with class .selected, and adds that item to the cart:
// selects the elements
$('.next').on('click', function() {
var parent = $(this).closest('.panel');
var selectables = parent.children('.option.selectable.selected');
$(selectables).each(function() {
var product = $(this).attr('product');
add_to_cart(product, 1);
});
}
// add to cart AJAX
function add_to_cart(product_id, qty) {
$.ajax({
type: "POST",
url: base_url + '/wp-admin/admin-ajax.php',
data: {action : 'cl_add_to_cart', 'product_id': product_id, 'qty': qty},
success : function(response) {
console.log(response);
}
});
}
And I have a PHP function in functions.php
add_action('wp_ajax_cl_add_to_cart', 'cl_add_to_cart');
add_action('wp_ajax_nopriv_cl_add_to_cart', 'cl_add_to_cart');
function cl_add_to_cart() {
global $woocommerce;
$product_id = trim($_POST['product_id']);
$qty = !empty($_POST['qty']) ? trim($_POST['qty']) : 1;
$added = WC()->cart->add_to_cart($product_id, $qty);
echo json_encode($added);
}
The AJAX call is hitting the PHP function just fine - I can echo out $added which gives me a hash. If I have two or more items in the selectables var, they both hit the PHP function (I get two hashes back) but only the first one gets added to the cart.
I can't for the life of me figure out why. Any ideas?