Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Add specific product with specific quantity with ajax on Woocommerce

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();

}

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!