Add quantity input in products list

Snippets

Sunday, 17 May 2020

One feature that you may find useful for your B2B shop is to add the quantity selection field in pages containing products list, such as in category pages.

To do this, edit functions.php file that you find in your site’s FTP space in:

 wp-content/themes/{YOUR_ACTIVE_THEME}/functions.php

and insert this code:

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() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="wcb2b-quantity" method="post" enctype="multipart/form-data">';
        $html .= woocommerce_quantity_input( array(), $product, false );
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}, 10, 2 );

Of course, you need to apply the styles needed to customize this field, to make it graphically compatible with your theme.

WARNING! Before making any changes, make sure you have made a complete backup of site files and database.
It is advisable not to edit the theme files directly, but to use a child theme.
For more information on child themes, please read: WordPress Official guide on Child Themes