WooCommerce分类显示需求:展示子分类与父分类商品(排除子分类商品)
Hey there, I get exactly what you're looking for—WooCommerce's default three options don't cover this specific case, but we can fix it with a bit of custom code. Let's break it down:
The Problem Recap
Right now, when you select "Show subcategories and products" in Appearance → Customize → WooCommerce → Product Catalog → Category display, it shows:
- All subcategories of the parent category
- Every product from the parent category AND all its subcategories
But you want to adjust this to only show:
- All subcategories of the parent category
- Only the products directly assigned to the parent category (not the ones in subcategories)
The Solution: Add a Custom Filter
We'll use WooCommerce's woocommerce_product_query_tax_query filter to modify the product query on category pages. This will tell WooCommerce to exclude products that belong to any child categories of the current parent category.
Add this code to your theme's functions.php file (or a custom plugin if you prefer, to avoid losing changes when updating your theme):
add_filter( 'woocommerce_product_query_tax_query', 'custom_category_display_exclude_subcategory_products', 10, 2 ); function custom_category_display_exclude_subcategory_products( $tax_query, $query ) { // Only target main parent category archives (not subcategory pages) if ( is_product_category() && ! is_product_category( get_terms( 'product_cat', array( 'parent' => get_queried_object_id(), 'fields' => 'slugs' ) ) ) ) { $current_category = get_queried_object(); // Fetch all child category IDs of the current parent $child_categories = get_terms( 'product_cat', array( 'parent' => $current_category->term_id, 'hide_empty' => false, 'fields' => 'ids' ) ); if ( ! empty( $child_categories ) ) { // Add rule to exclude products linked to child categories $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $child_categories, 'operator' => 'NOT IN', ); } } return $tax_query; }
How This Works
- The code first checks if we're on a parent product category page (it won't affect subcategory pages themselves).
- It grabs all child categories associated with the current parent category.
- It adds a tax query rule that filters out any products assigned to those child categories.
- The end result: your parent category page will display all subcategories plus only the products directly assigned to the parent (no products from subcategories will show up).
Final Steps
- Save your changes to
functions.php(or activate your custom plugin if you used that route). - Head to your parent category page on the frontend—you’ll now see exactly what you wanted: subcategories alongside the parent category’s own products, with no subcategory products included.
内容的提问来源于stack exchange,提问作者Hide S

