如果数量超过产品库存,Woocommerce 如何添加消息

Woocommerce how to add message if quantity exceeds product stock

我在 woocommerce 商店有延期交货的产品。

如果数量输入字段的值是 higher/exceeds 产品库存,我正在尝试创建一条错误消息 - 请参见下图。

如果客户低于当前库存,我也希望这种情况消失。

如果可能的话,我也希望错误也显示在购物车页面中。

到目前为止我得到的是:


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
}

请看这个:

  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) 将 return 您的消息现在您可以 set/print 相应地发送此消息。