试图列出产品类别以及产品的价格范围



我正在尝试创建一个页面,其中显示类别列表和这些类别中产品的价格范围。

头饰- 30- 150英镑

鞋子-£35-£300

,"Headwear"为产品类别名称,"£30";是同类产品的最低价格和"150英镑";是最高的。

到目前为止,我已经使用以下代码列出了类别,但不确定如何检查每个类别中的产品并获得价格等。

$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby'    => $orderby,
'order'      => $order,
'hide_empty' => $hide_empty,
);

$product_categories = get_terms( 'product_cat', $cat_args );

if( !empty($product_categories) ){
echo '

<ul>';
foreach ($product_categories as $key => $category) {
echo '

<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>


';
}

我在Woocommerce方面相当缺乏经验,所以任何帮助都将非常感谢

您可以使用以下代码段(来源:https://www.businessbloomer.com/woocommerce-get-return-all-product-ids/):

)获得按产品类别段的产品列表
$all_ids = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'your_product_cat',
'operator' => 'IN',
)
),
));

因此,对于每个类别,您可以遍历产品并找到最便宜和最昂贵的产品:

$min = PHP_FLOAT_MAX;
$max = 0.00;
foreach ( $all_ids as $id ) {
$product = wc_get_product( $id );
$min = $product->get_price() < $min ? $product->get_price() : $min;
$max = $product->get_price() > $max ? $product->get_price() : $max;
}

现在连同你的代码:

$order = 'asc';
$hide_empty = false;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);   
$product_categories = get_terms( 'product_cat', $cat_args );
if ( ! empty( $product_categories ) ) {
echo '<ul>';
foreach ( $product_categories as $key => $category ) {
$all_ids = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category->slug,
'operator' => 'IN',
)
),
));
$min = PHP_FLOAT_MAX;
$max = 0.00;
foreach ( $all_ids as $id ) {
$product = wc_get_product( $id );
$min = wc_format_decimal( $product->get_price() ) < $min ? wc_format_decimal( $product->get_price() ) : $min;
$max = wc_format_decimal( $product->get_price() ) > $max ? wc_format_decimal( $product->get_price() ) : $max;
}
echo '<li><a href="' . get_term_link( $category ) . '">';
echo $category->name . ' - ' . wc_price( $min ) . '-' . wc_price( $max );
echo '</a></li>';
}
echo '</ul>';
}

最新更新