在 WordPress 中,有很多方法可以做到这一点。您可以使用 WP_Query 对象执行自定义查询来获取该类别中的所有产品,这将是最灵活的选项,但还有一种更简单的方法。
Woocommerce 提供专门用于显示特定类别中的产品的短代码。输出将使用 Woocommerce 中已内置的模板。
<?php echo do_shortcode('[product_category category="appliances"]');?>
这将为您提供特定类别下的产品。
在您的代码中,您可能会执行以下操作:
<ul class="wsubcategs">
<?php
$wsubargs = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $category->term_id,
'taxonomy' => 'product_cat'
);
$wsubcats = get_categories($wsubargs);
foreach ($wsubcats as $wsc):
?>
<li>
<a href="<?php echo get_term_link( $wsc->slug, $wsc->taxonomy );?>"><?php echo $wsc->name;?></a>
<div class="products">
<?php echo do_shortcode('[product_category category="'.$wsc->slug.'"]');?>
</div>
</li>
<?php endforeach;?>
</ul>
我在你的问题中注意到你正在输出一个列表。在我看来,您可能不想在每个类别下实际输出产品(详细模板),但您可能更想在子列表中显示产品或产品标题的数量。
显示产品数量的方法如下:
count;?>
您可以在上面的 foreach 循环中的任何位置使用它。
以下是在每个类别的列表元素中显示产品标题子列表的方法:
<?php $subcategory_products = new WP_Query( array( 'post_type' => 'product', 'product_cat' => $wsc->slug ) );
if($subcategory_products->have_posts()):?>
<ul class="subcat-products">
<?php while ( $subcategory_products->have_posts() ) : $subcategory_products->the_post(); ?>
<li>
<a href="<?php echo get_permalink( $subcategory_products->post->ID ) ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile;?>
</ul>
<?php endif; wp_reset_query(); // Remember to reset ?>
这是上面代码中的样子:
<ul class="wsubcategs">
<?php
$wsubargs = array(
'hierarchical' => 1,
'show_option_none' => '',
'hide_empty' => 0,
'parent' => $category->term_id,
'taxonomy' => 'product_cat'
);
$wsubcats = get_categories($wsubargs);
foreach ($wsubcats as $wsc):
?>
<li>
<a href="<?php echo get_term_link( $wsc->slug, $wsc->taxonomy );?>"><?php echo $wsc->name;?></a>
<?php $subcategory_products = new WP_Query( array( 'post_type' => 'product', 'product_cat' => $wsc->slug ) );
if($subcategory_products->have_posts()):?>
<ul class="subcat-products">
<?php while ( $subcategory_products->have_posts() ) : $subcategory_products->the_post(); ?>
<li>
<a href="<?php echo get_permalink( $subcategory_products->post->ID ) ?>">
<?php the_title(); ?>
</a>
</li>
<?php endwhile;?>
</ul>
<?php endif; wp_reset_query(); // Remember to reset ?>
</li>
<?php endforeach;?>
</ul>