简体   繁体   English

如何获取每个变体的库存数量 woocommerce

[英]How to get each variation's stock quantity woocommerce

I'm showing product variations as a list instead of a drop down using the code below (may help some people).我使用下面的代码将产品变体显示为列表而不是下拉列表(可能对某些人有所帮助)。 What I'm trying to add to this is the stock count for each variation.我要添加的是每个变体的库存数量。

Ie something like this would be ideal to drop in.即这样的东西将是理想的下降。

<?php echo $product->get_stock_quantity(); ?>

Current code using to display variations in a table/list.当前代码用于显示表格/列表中的变化。

function woocommerce_variable_add_to_cart() {
    global $product, $post;
    $variations = $product->get_available_variations();
    foreach ($variations as $key => $value) {
    ?>
    <form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>"method="post" enctype='multipart/form-data'>
        <input type="hidden" name="variation_id" value="<?php echo $value['variation_id']?>" />
        <input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
        <?php
        if(!empty($value['attributes'])){
            foreach ($value['attributes'] as $attr_key => $attr_value) {
            ?>
            <input type="hidden" name="<?php echo $attr_key?>" value="<?php echo $attr_value?>">
            <?php
            }
        }
        ?>
        <table>
            <tbody>
                <tr>
                    <td>
                        <b><?php echo implode('/', $value['attributes']);?></b>
                    </td>
                    <td>
                        <?php echo $value['price_html'];?>
                    </td>
                    <td>

                    </td>
                    <td>
                        <button type="submit" class="single_add_to_cart_button button alt"><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></button>
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
    <?php
    }
}

You can access the stock of product variations with the following:您可以通过以下方式访问产品变体的库存:

<?php

global $product;


     if ( $product->is_type('variable') ) {

     foreach ( $product->get_visible_children() as $variation_id ) {

     //gets the product variation based on its id
     $get_product_variation = wc_get_product( $variation_id );

     //get each variations stock quantity
     $product_variation_stock = $get_product_variation->get_stock_quantity();

     //do whatever with variation stock
     echo '<p> Variation: ' . $variation_id . ' - Stock: ' . $product_variation_stock . '</p>';

     }
  }

 ?>

Hope that helps.希望有帮助。 Tested and works.测试和工作。 Good luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM