如何在WooCommerce分类页面展示子分类及对应下方产品列表
WooCommerce父分类页按子分类分组展示商品实现方案
前置注意事项
- 所有修改均建议在子主题下操作,避免更新WooCommerce或站点主题时覆盖自定义代码
- 修改前提前备份站点文件与数据库,防止操作异常影响线上业务
实现方案:覆盖WooCommerce分类归档模板
WooCommerce默认的分类归档模板为archive-product.php,你可以将该文件从WooCommerce插件的templates目录复制到子主题的woocommerce目录下,再替换原有商品输出逻辑即可。
核心代码逻辑
找到模板中原先输出商品列表的代码段,替换为以下内容:
// 获取当前访问的父分类对象 $current_cat = get_queried_object(); // 查询当前分类的直属子分类 $child_cats = get_terms( array( 'taxonomy' => 'product_cat', 'parent' => $current_cat->term_id, 'hide_empty' => true, ) ); if ( ! empty( $child_cats ) ) : // 存在子分类时按子分类分组输出 foreach ( $child_cats as $child_cat ) : // 输出子分类标题 echo '<h2 class="child-category-title">' . esc_html( $child_cat->name ) . '</h2>'; // 查询该子分类下的全部商品 $product_args = array( 'post_type' => 'product', 'posts_per_page' => -1, // 展示所有商品,可自行修改为固定数量 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $child_cat->term_id, 'include_children' => false, // 不包含子分类的下级分类,可按需开启 ) ), 'post_status' => 'publish' ); $products = new WP_Query( $product_args ); if ( $products->have_posts() ) : // 调用WooCommerce默认商品循环模板,保持与站点原有商品样式一致 woocommerce_product_loop_start(); while ( $products->have_posts() ) : $products->the_post(); wc_get_template_part( 'content', 'product' ); endwhile; woocommerce_product_loop_end(); else : echo '<p class="woocommerce-info">该分类下暂无商品</p>'; endif; wp_reset_postdata(); endforeach; else : // 无对应子分类时走默认商品展示逻辑 if ( woocommerce_product_loop() ) { do_action( 'woocommerce_before_shop_loop' ); woocommerce_product_loop_start(); if ( wc_get_loop_prop( 'total' ) ) { while ( have_posts() ) { the_post(); do_action( 'woocommerce_shop_loop' ); wc_get_template_part( 'content', 'product' ); } } woocommerce_product_loop_end(); do_action( 'woocommerce_after_shop_loop' ); } else { do_action( 'woocommerce_no_products_found' ); } endif;
样式调整
如果需要区分子分类标题和商品区块,可在主题自定义CSS面板添加如下样式:
.child-category-title { margin: 40px 0 20px 0; padding-bottom: 10px; border-bottom: 1px solid #eee; }
可选优化
- 若需要隐藏父分类下直接挂载、不属于任何子分类的商品,可在查询逻辑中添加对应排除规则
- 若商品数量较多需要分页,可调整
posts_per_page参数,配合WooCommerce原生分页函数实现分页功能
内容的提问来源于stack exchange,提问作者Javier
相关产品推荐
相关产品推荐

