I am Unable to add a product variation to cart using jQuery and Ajax. With the code below, the parent variable product is added, but not the variation.
For example, I specified one of T-shirt variations (blue) with price of 45$, but at the end, the parent is added with price of 30$.
Cart should show: T-shirt – Blue 45$, but instead it shows: T-shirt 30$.
My code so far:
jQuery(document).ready(function($) {
$(document.body).on('click', '#button', function(e) {
const data = {
product_id: 592,
quantity: 2,
variation_id: 1017,
};
$.ajax({
type: 'POST',
url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add_to_cart' ),
data: data,
success: function(res) {
console.log('added');
},
});
});
});
How to accomplish this with jQuery?
2
Answers
If you look at
WC_Ajax
add_to_cart
method (line 470 to 474), you will see the following:Which means that you don’t really need to set in your code the main variable product Id, but you can just set the variation ID as product ID argument and the quantity like:
Tested and works with a real variation ID.
To follow on from LoicTheAztec’s answer. I needed to include the
variation_id
otherwise the function add_to_cart_handler_variable would complain and add a wc notice to the frontend.I don’t know why one area of WC seems to support variable products whilst another doesn’t; when adding to the cart like this.
So: