1

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
}
Ruvee
  • 8,611
  • 4
  • 18
  • 44
Blomshit
  • 17
  • 1
  • 1
  • 5

1 Answers1

1

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.

Rajeev Singh
  • 1,724
  • 1
  • 6
  • 23
  • Thank you very much @Rajeev, this was exactly what I was looking to do! I still don't manage to get this to work on the cart page, but it will be suffiecient for now. You saved the day! – Blomshit Sep 14 '21 at 12:02
  • Thanks, you can also check this one - https://www.businessbloomer.com/woocommerce-automatically-update-cart-quantity-change/ – Rajeev Singh Sep 14 '21 at 12:08