WooCommerce:检查产品是否缺货并且不允许延期交货
如何检查产品是否缺货(库存数量为 0)且不允许延期交货?以下代码由于某种原因不起作用.
How do I check if a product is out of stock (stock quantity 0) and doesn't allow backorders? The following code doesn't work for some reason.
add_action('woocommerce_before_add_to_cart_button','show_stock_single');
function show_stock_single() {
global $product;
if($product->get_stock_quantity()<1) {
if($product->backorders_allowed()) echo '<p>Backorders allowed</p>';
else echo '<p>Backorders not allowed</p>';
}
else echo '<p>Available</p>';
}
对于允许延期交货的产品,它显示允许延期交货",但如果不允许延期交货,则不显示任何内容.为什么?
It shows "backorders allowed" for products that allow backorders, but nothing if backorders are not allowed. Why?
每当我得到一个没有按照我认为应该做的 if 语句时,我尝试的第一件事就是反转它,所以试一试...
Whenever I get an if statement that's not doing as I think it should, the first thing I try is to reverse it, so give this a go...
if($product->get_stock_quantity()>0) {
echo '<p>Available</p>';
} else {
if($product->backorders_allowed()) {
echo '<p>Backorders allowed</p>';
} else {
echo '<p>Backorders not allowed</p>';
}
}
- 我还要确保您将各种 if 位与 {...} 括号括起来.我知道 PHP 应该允许更宽松的单行 ifs 要求,但这可能是原因!
- I'd also make sure you're enclosing the various if bits with the {...} brackets. I know PHP is supposed to allow a more relaxed requirement with single line ifs, but it might be the cause!