我想在我的主页显示8个类别X的产品
我使用以下代码来获取产品
<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();
方法来显示产品价格。WC_Product
为什么? 因为在这两种情况下你会得到错误的价格:
- 如果您已输入价格含税并且您已设置显示不含税...
- 如果您已输入价格不含税并且您已设置显示含税。
所以显示产品价格正确的方法是使用
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() ) ) );
您可以使用 get_sale_price 获取促销价,使用 get_regular_price 获取正常价格
$product->get_sale_price();
$product->get_regular_price();