WooCommerce商店隐藏指定分类商品问题求助
解决WooCommerce隐藏「Testing」分类商品的问题
问题说明
需要隐藏所有包含「Testing」分类的商品(无论商品是否同时属于其他分类),但尝试了三段代码后商品仍在商店页面显示。
现有代码的问题分析
- 第一段
ts_get_subcategory_terms:仅隐藏了分类导航中的「Testing」标签,并未真正过滤商品列表,所以商品依然会显示。 - 第二段
custom_pre_get_posts_query:- 条件
is_post_type_archive范围太窄,没覆盖商品分类页、标签页等场景; - 函数内调用
remove_action会导致该钩子只执行一次,后续页面查询不会生效; - 直接覆盖
tax_query可能和WooCommerce的默认查询冲突,没有合并现有查询条件。
- 条件
- 第三段
hide_category:同样只是处理分类术语的显示,不影响商品本身的查询结果。
正确解决方案
方案1:使用pre_get_posts钩子(通用WordPress查询过滤)
这个钩子能覆盖所有前端商品查询场景,同时确保只要商品包含「Testing」分类就被排除:
add_action( 'pre_get_posts', 'exclude_testing_category_products' ); function exclude_testing_category_products( $query ) { // 只处理前端的主查询,且是商品类型的查询 if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() || is_product_taxonomy() ) ) { // 获取现有tax_query,避免覆盖其他查询条件 $tax_query = $query->get( 'tax_query', array() ); // 添加排除「Testing」分类的条件 $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array( 'testing' ), 'operator' => 'NOT IN', // 关键:确保商品只要有这个分类就被排除,即使有其他分类 'include_children' => false // 如果不需要排除子分类可以设为true ); $query->set( 'tax_query', $tax_query ); } }
方案2:使用WooCommerce专属钩子woocommerce_product_query
针对WooCommerce的商品查询,这个钩子更精准:
add_action( 'woocommerce_product_query', 'exclude_testing_category_from_woocommerce' ); function exclude_testing_category_from_woocommerce( $query ) { if ( ! is_admin() ) { $tax_query = $query->get( 'tax_query', array() ); $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array( 'testing' ), 'operator' => 'NOT IN', 'include_children' => false ); $query->set( 'tax_query', $tax_query ); } }
额外注意事项
- 确保代码添加到主题的
functions.php文件,或者使用自定义代码插件(如Code Snippets); - 清除WooCommerce缓存和WordPress缓存,避免旧的查询结果残留;
- 确认「Testing」分类的slug确实是
testing(可在后台分类编辑页面查看); - 如果需要排除该分类下的子商品,把
include_children设为true。
内容的提问来源于stack exchange,提问作者Kristi Perkins
相关产品推荐
相关产品推荐

