获取要在 WooCommerce 3 中显示的产品价格

Get product prices to be displayed in WooCommerce 3

我想在我的首页显示类别 X 的 8 个产品

我使用以下代码获取产品

    <div class="row">
        <?php  
            $args = array(
                'post_type'      => 'product',
                'posts_per_page' => 8,
                'product_cat'    => 'cw'
            );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
                global $product;
        ?>

        <div class="col-md-3">
            <div class="product">
                <?php echo woocommerce_get_product_thumbnail(); ?>
                <p class="name"><?php echo get_the_title(); ?></p>
                <p class="regular-price"></p>
                <p class="sale-price"></p>
                <a href="<?php echo get_permalink(); ?>" class="more">more info</a>
                <form class="cart" action="<?php echo get_permalink(); ?>" method="post" enctype='multipart/form-data' style="display:inline;">
                    <button type="submit" name="add-to-cart" value="45" class="order">buy</button>
                </form>
            </div>
        </div>

有了这个我可以得到产品,但我不知道用什么方法得到正常和销售价格

您可以使用 get_sale_price 的促销价和 get_regular_price 的正常价格

$product->get_sale_price();

$product->get_regular_price();

Never use directly get_sale_price(); or get_regular_price(); WC_Product methods to display product prices.

Why? Because you will get the wrong prices in that 2 cases:

  • If you have enter your prices with taxes and you have set the display without taxes
  • If you have enter your prices without taxes and you have set the display with taxes.

所以显示产品价格正确的方法是wc_get_price_to_display()这样使用:

// Active price: 
wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) );

//Regular price: 
wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );

//Sale price: 
wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );

现在,如果您想要 正确格式化的货币价格,您还可以这样使用 wc_price() 格式化功能:

// Active formatted price: 
$product->get_price_html();

// Regular formatted  price: 
wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) );

// Sale formatted  price: 
wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ) );