获取并显示 WooCommerce 3 中的可变产品价格范围



我对wordpress和woocommerce很陌生。 我正在修改二十七主题的搜索结果页面,使其看起来像一个表格。 大多数产品都是可变产品。我使用下面的代码在表格中显示结果

<table class="search-res" style="table-layout: auto; width: 100%;">
<tr><td>
<?php
if ( has_post_thumbnail()) 
the_post_thumbnail('excerpt-thumb');        
?></td>
<td>
<?php 
the_title( sprintf( '<th class="entry-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ) );
echo"</a></th>";
?>
</td>
<td style="font-style:italic;font-size:small;"><?php the_excerpt(); ?></td>
<th><?php 
global $post;
$product = new WC_Product($post->ID ); 
echo wc_price($product->get_price_including_tax(1,$product->get_price()));
?></th>
</tr>
</table>

我面临的问题是在这里显示产品的最低价格。相反,我希望价格范围显示出来。 另外,如何让商品的评分和类别属性显示在表格中?

你只需要使用WC_Product_Variableget_price_html()的方法就可以为你做到这一点:

<?php
global $post;
// Get the WC_Product_Variable instance Object
$product = wc_get_product( $post->ID ); // Works for any product type
// Displaying the formatted "Min" - "Max" price range
echo $product->get_price_html();
?>

经过测试和工作

想通了。 这不是理想的方法,我确信有一种更简单的方法来做事,但仍然是我的解决方法:

<?php
global $post;
$parent_product=new WC_Product_Variable($post->ID);
$variations=$parent_product->get_children();
$max_price=0;
$min_price=10000;
foreach ($variations as $product){
$single_variation=new WC_Product_Variation($product);
if($single_variation->price > $max_price){
$max_price=$single_variation->price;
}
if($single_variation->price < $min_price){
$min_price=$single_variation->price;
}
}
echo get_woocommerce_currency_symbol().$min_price.'-'.get_woocommerce_currency_symbol().$max_price; 
?>

最新更新