問題描述
使用 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。