WooCommerce默认循环下如何在商店首页排除指定产品分类
之前代码失效原因
- 第一段代码挂载的
woocommerce_shortcode_products_query钩子仅作用于商品短代码查询,你使用的是默认首页循环,逻辑完全不会触发。 - 第二段代码存在三处错误:
- 判断条件中设置了
is_shop() return $query,如果你的首页就是商店主页面,会直接跳过排除逻辑 - 直接覆盖
tax_query参数,会丢失WooCommerce默认的查询条件,引发其他逻辑异常 - 执行一次就移除了钩子,分页或同页面其他后续查询无法生效
- 判断条件中设置了
可用解决方案
根据你首页的展示内容选择对应代码,添加到主题functions.php文件或自定义代码片段插件中即可:
场景1:首页展示产品列表,需排除指定分类下的产品
add_filter( 'pre_get_posts', 'custom_exclude_product_cat_from_home', 999 ); function custom_exclude_product_cat_from_home( $query ) { // 仅前台首页主查询生效 if ( is_admin() || ! $query->is_main_query() || ! is_front_page() ) { return $query; } // 合并原有查询条件,避免覆盖默认规则 $tax_query = $query->get( 'tax_query' ) ? : []; $tax_query[] = [ 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => 122, 'operator' => 'NOT IN' ]; $query->set( 'tax_query', $tax_query ); return $query; }
场景2:首页展示产品分类目录,需排除指定分类项本身
add_filter( 'get_terms', 'custom_hide_product_cat_from_home_list', 999, 3 ); function custom_hide_product_cat_from_home_list( $terms, $taxonomies, $args ) { // 仅前台首页查询产品分类时生效 if ( is_admin() || ! is_front_page() || ! in_array( 'product_cat', $taxonomies ) ) { return $terms; } // 移除ID为122的分类 foreach ( $terms as $key => $term ) { if ( isset( $term->term_id ) && $term->term_id === 122 ) { unset( $terms[$key] ); } } return $terms; }
注意事项
- 如果你的首页设置为默认商店页而非静态首页,将代码中的
is_front_page()替换为is_shop()即可 - 代码添加后需清空WooCommerce缓存、站点缓存、浏览器缓存后再测试效果
- 建议使用子主题的
functions.php存放自定义代码,避免主题更新后代码被覆盖
内容的提问来源于stack exchange,提问作者DaveDesigns
相关产品推荐
相关产品推荐

