How to grouped/bundle products using ajax in Woocommerce

  php, woocommerce, wordpress

I am trying to add grouped/bundle products in cart. I used custom function for trigger add to cart event. I used wp-admin/admin-ajax.php to call api endpoint. It is working correct for simple and variation type products.

For grouped products, I am trying to post ajax dynamically for multiple items. Please review below code:

let groupedProductElements = document.getElementsByClassName('woocommerce-grouped-product-list-item');
            [...groupedProductElements].forEach(function (ele){
                let productAttr = ele.getAttribute('id');
                let productData = productAttr.split('-');
                let formData = new FormData();
                formData.append("action", "add_to_cart");
                formData.append("product_id", productData[1]);
                formData.append("quantity",ele.querySelector('[id^="quantity_"]').value);
                jQuery.ajax({
                    type: 'post',
                    url: admin_ajax_url,
                    data: formData,
                    processData: false,
                    contentType: false,
                    complete: function(response) {
                        console.log(response);
                    },
                   
                });

            });

PHP code to add product into cart:

function add_to_cart()
{ 
    // Check if post parameters have product_id and quantity
    if (isset($_POST['product_id'], $_POST['quantity'])) {
        $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
        $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
        $variation_id = absint($_POST['variation_id']);
        $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
        $product_status = get_post_status($product_id);

        // If validation passed then add item into cart
        if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
            do_action('woocommerce_ajax_added_to_cart', $product_id);
            echo $this->get_cart_details();
        }
        wp_die();
    }
}

Even when I click on custom_add_to_cart button It will show success admin-ajax calls for multiple products but sometimes added all products but sometimes add single product only.

I also tried to search similar questions but didn’t get proper solution. Please suggest if you guys have any solution. TIA

Source: Ask PHP

LEAVE A COMMENT