WooCommerce:如何排除商品页面产品分类并隐藏分类菜单
嘿,我来帮你把这两个WooCommerce功能的代码补全并优化,直接看下面的实现:
一、隐藏产品分类菜单小工具中的指定分类
你之前写的代码逻辑有点小问题,比如当include参数为空时,explode会报错,我帮你调整成更稳妥的版本,直接针对分类小工具排除指定分类ID:
add_filter( 'woocommerce_product_categories_widget_args', 'rv_exclude_wc_widget_categories' ); function rv_exclude_wc_widget_categories( $cat_args ) { // 这里填你要排除的产品分类ID,多个的话用逗号分隔,比如 array('129', '130') $exclude_ids = array('129'); // 处理exclude参数,如果原本已有排除项,合并进去 if ( !empty($cat_args['exclude']) ) { // 把原本的exclude转成数组(可能是字符串) $existing_exclude = is_array($cat_args['exclude']) ? $cat_args['exclude'] : explode(',', $cat_args['exclude']); $cat_args['exclude'] = array_merge($existing_exclude, $exclude_ids); } else { $cat_args['exclude'] = $exclude_ids; } // 不需要处理include,因为exclude本身就会过滤掉指定分类 return $cat_args; }
说明:这个代码会作用于WooCommerce自带的「产品分类」小工具,直接把指定ID的分类从菜单里隐藏掉。
二、在商品页面排除指定产品分类
这个需求需要修改WooCommerce的主查询,让商品归档页面(比如Shop首页、分类列表页)不显示指定分类下的产品,补全你没写完的查询逻辑:
add_action( 'pre_get_posts', 'exclude_category_from_product_pages' ); function exclude_category_from_product_pages( $query ) { // 只针对前台的产品查询生效,避免影响后台操作 if ( !is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() ) ) { // 这里填要排除的分类ID,多个的话直接在数组里添加,比如 array('129', '130') $query->set( 'tax_query', array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => array('129'), 'operator' => 'NOT IN', ) ) ); } }
说明:这段代码会让Shop页面、所有产品分类页面都不展示指定分类下的产品,如果你只想在Shop首页排除,把( is_shop() || is_product_category() )改成is_shop()即可。
把这两段代码添加到你的主题functions.php文件里,或者用自定义代码插件添加,就能实现你要的两个功能啦。
内容的提问来源于stack exchange,提问作者benjiiiii
相关产品推荐
相关产品推荐

