How To Add Woocommerce Add To Cart Quantity Plus & Minus Buttons

How To Add Woocommerce Add To Cart Quantity Plus & Minus Buttons.

WordPress provides plenty of woocommerce themes, and every theme has a different way of laying out and styling the different features for an e-commerce store. In this topic learn about how can we add the quantity feature more specifically about the buttons that we can click to increase and decrease the quantity of a product.

We can use a simple code of PHP, JQuery, and CSS to add plus and minus buttons in place of the up and down arrows to increase and decrease the quantity. Here is the adding simple code in your child theme functions.php file.

add_action( 'woocommerce_after_add_to_cart_quantity', 'tch_quantity_plus_sign' );
 
function tch_quantity_plus_sign() {
   echo '<button type="button" class="plus" >+</button>';
}
 
add_action( 'woocommerce_before_add_to_cart_quantity', 'tch_quantity_minus_sign' );
function tch_quantity_minus_sign() {
   echo '<button type="button" class="minus" >-</button>';
}
 
add_action( 'wp_footer', 'tch_quantity_plus_minus' );
 
function tch_quantity_plus_minus() {

   if ( ! is_product() ) return;
   ?>
   <script type="text/javascript">
          
      jQuery(document).ready(function($){   
          
            $('form.cart').on( 'click', 'button.plus, button.minus', function() {
 
            // Get current quantity values
            var qty = $( this ).closest( 'form.cart' ).find( '.qty' );
            var val   = parseFloat(qty.val());
            var max = parseFloat(qty.attr( 'max' ));
            var min = parseFloat(qty.attr( 'min' ));
            var step = parseFloat(qty.attr( 'step' ));
 
            // Change the value if plus or minus
            if ( $( this ).is( '.plus' ) ) {
               if ( max && ( max <= val ) ) {
                  qty.val( max );
               } 
            else {
               qty.val( val + step );
                 }
            } 
            else {
               if ( min && ( min >= val ) ) {
                  qty.val( min );
               } 
               else if ( val > 1 ) {
                  qty.val( val - step );
               }
            }
             
         });
          
      });
          
   </script>
   <?php
}

After adding the above code output is displayed like this:

Here we can see the output of the plus (+) and minus (-) to the added product quantity.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories