尝试列出产品类别及其产品的价格范围

Attempting to List Product Categories along with the price range of their products

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

例如

头饰 – £30-£150

鞋子 – £35-£300

其中“头饰”是产品类别名称,“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>';
}