Search code examples
wordpresswoocommerceproductstockwoocommerce-theming

Woocommerce how to add message if quantity exceeds product stock


I am having products on backorder in a woocommerce store.

I am trying to create an error message if the value of the quantity input field is a higher/exceeds the products stock - see image below.

I also want this to go away if the customer goes below current stock.

If possible I also want the error to show in the cart page as well.

enter image description here

This is what I got this far:


function woocommerce_stock_now() {
    
    
    global $woocommerce, $product;
    ?>
<script>
    jQuery(function ($) {

        var stocknow = <?php echo $qty = $product->get_stock_quantity()(); ?>;        
                    
        var qtyinput = $('[name=quantity]').val();
        var errormessagestock = '<p class="errormessagestock">'(stocknow.value - qtynow.value) . ' items are on backorder and will have a little longer delivery time.</p>';
        
        $('#qtyinput').html(this.value);
        
        $('[name=quantity]').change(function () {
            if (qtyinput.value > $stocknow) {

                $('stock').html(errormessagestock);
 
                } 
        });


        console.log("qtynow", this.value);

    });
</script>
<?php
}

Solution

  • Tyr this:

      add_action( 'woocommerce_single_product_summary', 'woocommerce_stock_now' ); 
      
      function woocommerce_stock_now() {
            global $product;
            $stocknow = $product->get_stock_quantity();
            ?>
            <script>
                  jQuery(document).on('input change','[name=quantity]',function() {
                        var stocknow = '<?php echo $stocknow; ?>';
                        var qtyinput = jQuery(this).val(); 
                        var overdue = parseInt(qtyinput) - parseInt(stocknow);
                        if (parseInt(qtyinput) > parseInt(stocknow)) {
                              var errormessagestock = '<p class="errormessagestock">('+overdue+') items are on backorder and will have a little longer delivery time.</p>';  
                              console.log(errormessagestock); 
                              //$('stock').html(errormessagestock);         
                        }
                  });
            </script>
            <?php 
      }
    

    console.log(errormessagestock) will return your message now you can set/print this message accordingly.