Add a quantity field to Ajax add to cart button on WooCommerce shop page

后端 未结 3 516
Happy的楠姐
Happy的楠姐 2021-01-02 23:03

I am new to Woocommerce. I was trying to show the quantity box in the shop page. I have used the below code and it\'s working as expected:

add_action( \'woo         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-02 23:41

    Here is an alternative method which seems to work well in Woo 3+

    is_sold_individually() && 'variable' != $product->get_type() && $product->is_purchasable() ) {
        woocommerce_quantity_input( array( 'min_value' => 1, 'max_value' => $product->backorders_allowed() ? '' : $product->get_stock_quantity() ) );
        }
    
    }
    add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 0, 9 );
    
    /**
     * Enqueue the JavaScript.
     */
    function custom_add_to_cart_quantity_handler() {
    
    wc_enqueue_js( '
        jQuery( ".post-type-archive-product" ).on( "click", ".quantity input", function() {
            return false;
        });
        jQuery( ".post-type-archive-product" ).on( "change input", ".quantity .qty", function() {
            var add_to_cart_button = jQuery( this ).parents( ".product" ).find( ".add_to_cart_button" );
            
            // For AJAX add-to-cart actions
            add_to_cart_button.attr( "data-quantity", jQuery( this ).val() );
    
            // For non-AJAX add-to-cart actions
            add_to_cart_button.attr( "href", "?add-to-cart=" +   add_to_cart_button.attr( "data-product_id" ) + "&quantity=" + jQuery( this ).val() );
        });
    ' );
    
    }
    add_action( 'init', 'custom_add_to_cart_quantity_handler' );
    

    There may be several options for the jQuery, depending on what Ajax actions are on your page.

提交回复
热议问题