问题描述
使用 WooCommerce,我想在商店中显示所有类别作为标题,其下面列出的所有产品都在无序列表中。这可以做吗?我看到一些东西,让我显示一个类别的列表或一个特定类别的产品列表,但没有什么会循环通过我所描述的方式。
以下是我目前用于列出所有类别的内容:
<?php
$args = array(
'number' => $number,
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
$count = count($product_categories);
if ( $count > 0 ){
foreach ( $product_categories as $product_category ) {
echo '<h4><a href="'%20.%20get_term_link(%20$product_category%20)%20.%20'">' . $product_category->name . '</h4>';
}
}
?>
最佳解决方案
弄清楚了!以下代码自动列出所有类别和每个类别的帖子!
$args = array(
'number' => $number,
'orderby' => 'title',
'order' => 'ASC',
'hide_empty' => $hide_empty,
'include' => $ids
);
$product_categories = get_terms( 'product_cat', $args );
$count = count($product_categories);
if ( $count > 0 ){
foreach ( $product_categories as $product_category ) {
echo '<h4><a href="'%20.%20get_term_link(%20$product_category%20)%20.%20'">' . $product_category->name . '</a></h4>';
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
// 'terms' => 'white-wines'
'terms' => $product_category->slug
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
$products = new WP_Query( $args );
echo "<ul>";
while ( $products->have_posts() ) {
$products->the_post();
?>
<li>
<a href="<?php%20the_permalink();%20?>">
<?php the_title(); ?>
</a>
</li>
<?php
}
echo "</ul>";
}
}
参考文献
注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。