php 如何从woocommerce获取文章的库存数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20244423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:59:59  来源:igfitidea点击:

How to get the stock quantity of an article from woocommerce?

phpwordpressfunctionwoocommercewoothemes

提问by Bill Bronson

i got a little problem with displaying the stock quantity correctly.

我在正确显示库存数量时遇到了一些问题。

heres the loop:

继承人循环:

 <?php
 /**
 * Loop Price
 *
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

global $product;
?>

<?php if ( $price_html = $product->get_price_html() ) : ?>
<span class="price">PREIS:<span class="amount"><?php echo $price_html; ?></span></span><p class="stock-m13"><?php get_sku(get_the_ID()); ?></p>
<?php endif; ?>

i want to show the user in the stock-m13 p the available quantity but im just gettin errors like "call to undefined function get_sku()".

我想在 stock-m13 p 中向用户显示可用数量,但我只是出现了诸如“调用未定义的函数 get_sku()”之类的错误。

what am i doing wrong? thx for any help.

我究竟做错了什么?感谢您的帮助。

回答by Steve

get_sku is a method of the product class, not a global function:

get_sku 是产品类的方法,不是全局函数:

$product->get_sku()

Note that this will just get the stock code, not the actual quantity, perhaps you want:

请注意,这只会获得股票代码,而不是实际数量,也许您想要:

$product->get_stock_quantity()

EDIT to clarify:

编辑以澄清:

<p class="stock-m13"><?php echo $product->get_stock_quantity(); ?></p>

回答by Sumith Harshan

I'm using as following.

我使用如下。

     <?php 
        global $product; 
        $numleft  = $product->get_stock_quantity(); 
        if($numleft==0) {
           // out of stock
            echo "There are no items available at this time."; 
        }
        else if($numleft==1) {
            echo "Only ".$numleft ." item left.";
        }
        else {
            echo "Only ".$numleft ." items left.";
        }
     ?>

Additional

额外的

Show total sold items.

显示已售商品总数。

     <?php 
       global $post;
       echo get_post_meta($post->ID, 'total_sales', true); 
     ?>

Hope this help. Thanks

希望这有帮助。谢谢

回答by meer panhyar

Simply add these lines in your single.php // your template for displaying he single post Or Id you want to display it on single product page

只需在 single.php 中添加这些行 // 用于显示单个帖子的模板或您想在单个产品页面上显示的 ID

Simply dd these lines in single-product.php in your theme directory

只需在主题目录中的 single-product.php 中添加这些行

 global $woocommerce;
 foreach($woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    if( get_the_ID() == $_product->id ) {
       echo 'Quantity Is'. $values['quantity'];// quantity of the product
    } 
  }