phpjquerywoocommerceproduct-quantity

WooCommerce - Add quantity selectors to the product archive


I created a button which hooks to the product loop in archive-products.php to allow customers to select/adjust the quantity amount which they add to cart.

When a user adds one product, it works fine, however if I try to add more, the button disappears from products which are output earlier in the loop.

How can i fix my code to stop the add to cart button disappearing?Adding the second item in the loop makes the previous disappear

add_filter( 'woocommerce_loop_add_to_cart_link', function ( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $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' : '',
        ) ) );

        $html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s ct-cart-actions">%s</a>%s',
        '<form class="cart">',
        woocommerce_quantity_input( array(), $product, false ),
        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' ),
        esc_html( $product->add_to_cart_text() ),
        '</form>'
        );
    }
    return $html;
}, 10, 2 );

add_action( 'wp_footer' , function (){
 if( is_home() || is_front_page() || is_shop() || is_product_category() || is_product_tag() ) { ?>
    <script type='text/javascript'>
        jQuery( document ).ready( function( $ ) {
        $( document ).on( 'change', '.quantity .qty', function() {
            $( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).attr( 'data-quantity', $( this ).val() );
        });
    });
        
        jQuery(function($) {
            $(".add_to_cart_button.product_type_simple").on('click', function() {
                var $button = $(this);
                $button.data('quantity', $button.parent().find('input.qty').val());
            });
            $(document.body).on("adding_to_cart", function() {
                $("a.added_to_cart").remove();
            });
        });
    </script>
<?php }
} );

Solution

  • Seemed like a Blocksy theme incompatibility. My solution was to replace

     $(document.body).on("adding_to_cart", function() {
        $("a.added_to_cart").remove();
    });
    

    with

     $(document.body).on("added_to_cart", function(event, fragments, cart_hash, $button) {
        $button.removeClass('added').addClass('loading');
    });
    

    Now works