How to fix quantity input field from affecting other quantity input fields on single product page woocommerce?

Viewed 41

We have added the code below to our functions.php file in Woocommerce. The goal was to replace the default Woocommerce "Add to Cart" button with a quantity selector and a cart icon that would act as the "Add to Cart" button. So far it has worked on every page as needed except for the single product page.

On our product page we have a quantity selector and an "add to cart" button that affects the product listed and below it is a list of 4 related products that each have their own quantity selector.

Here is an example

The issue that we are having is that if you change any of the quantities, all other quantities are changed as well.

/*Adds Quantity to product archive*/

add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 );
function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        // Get the necessary classes
    $class = implode( ' ', array_filter( array(
            'button',
            'product_type_' . $product->get_type(),
            $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
            $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
        ) ) );

        // Adding embeding <form> tag and the quantity field
        $html = sprintf( '%s%s%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>%s',
        '<form class="cart">',
    '<div class="form_cart_first_half">',
        woocommerce_quantity_input( array(), $product, false ),
    '</div>',
        esc_url( $product->add_to_cart_url() ), 
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        esc_attr( $product->get_id() ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $class ) ? $class : 'button' ),
        '<button type="submit" class="button alt" id="pa_add_to_cart_button">' . sprintf('<i class="fas fa-shopping-cart" id="pa_add_to_cart_button_icon" style="font-size:24px; display: inline-block;"></i>') . '</button>',
        '</form>'
        );
    }
    return $html;
}

If anyone has any suggestions on how to fix this I would appreciate it.

Thank you for your time.

0 Answers
Related