I have a custom selector on a Woocommerce product page, and when the user clicks on Add to cart, I want to catch the selector value using jQuery and pass it to php, then add a specific product to the cart.
I was able to do the jQuery part and get the selector value, but when trying to add the specific product with php, woocommerce is adding the product that is on the product page and not the product I want to add. Here is the jQuery file:
Query(document).on('click','.single_add_to_cart_button',function(e){
var productsNumber = jQuery(document).find('.custom-bundle').attr("products-number")
console.log("add to cart event");
//var productsNumber = jQuery(this).attr("products-number");
jQuery.ajax({
url: wbdl_ajax.ajaxurl,
type: "POST",
dataType : "json",
data: {
action: 'get_products_number',
products_num: productsNumber
},
success: function(response) {
//console.log(response)
if(response.type == "success") {
//console.log("Your vote has been added")
}
else {
//console.log("Your vote could not be added")
}
}
});
});
And the php:
add_action( 'wp_ajax_get_products_number', 'wbdl_get_products_number' ); add_action('wp_ajax_nopriv_get_products_number', 'wbdl_get_products_number');
function wbdl_get_products_number() {
global $woocommerce;
global $post;
$post_id = $_POST['product_id'];
$product_cart_id = WC()->cart->generate_cart_id( $post_id );
$cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
//$woocommerce->cart->add_to_cart( 20632 );
WC()->cart->add_to_cart(20632,4);
//do_action('woocommerce_ajax_added_to_cart', 21907);
//WC_AJAX :: get_refreshed_fragments();
wp_die();
}