使用WooCommerce与Elementor Anywhere排除指定分类商品问题求助
解决Elementor Post Blocks Adv排除WooCommerce特定分类无效的问题
你的代码核心问题有两个:使用了不存在的自定义过滤器钩子,以及直接覆盖原有查询参数导致与归档页默认筛选冲突,以下是具体修正方案:
1. 替换为正确的过滤器钩子
Post Blocks Adv作为Elementor扩展,需要使用Elementor官方提供的查询钩子,或者结合WooCommerce的产品查询钩子,而非自定义的filtre_zero_dechet(该钩子无对应触发逻辑,代码完全不生效)。
2. 修正查询参数的合并逻辑
原代码直接赋值meta_query会覆盖归档页原有的筛选条件,需合并原有参数;同时tax_query要确保和当前归档页的分类查询兼容,避免冲突。
方案一:Elementor专属钩子(仅作用于Post Blocks组件,推荐)
function filtrer_produit_sans_crea( $query_args ) { // 仅针对WooCommerce产品类型生效 if ( isset( $query_args['post_type'] ) && $query_args['post_type'] === 'product' ) { // 合并原有meta_query,避免覆盖归档页默认筛选 if ( ! isset( $query_args['meta_query'] ) ) { $query_args['meta_query'] = array(); } $query_args['meta_query'][] = array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=', ); // 合并原有tax_query,添加排除分类条件 if ( ! isset( $query_args['tax_query'] ) ) { $query_args['tax_query'] = array(); } // 多分类条件默认用AND逻辑,确保与原有筛选兼容 if ( ! isset( $query_args['tax_query']['relation'] ) ) { $query_args['tax_query']['relation'] = 'AND'; } $query_args['tax_query'][] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'coin-des-creatrices', 'operator' => 'NOT IN', ); } return $query_args; } // 绑定Elementor Post Blocks的查询钩子 add_filter( 'elementor/query/query_args', 'filtrer_produit_sans_crea' );
方案二:WooCommerce全局产品查询钩子(所有产品查询场景生效)
function filtrer_produit_sans_crea( $q ) { // 仅在前台产品归档页的主查询中生效 if ( ! is_admin() && $q->is_main_query() && $q->is_post_type_archive( 'product' ) ) { // 添加库存筛选 $q->set( 'meta_query', array( array( 'key' => '_stock_status', 'value' => 'instock', 'compare' => '=', ) ) ); // 获取原有分类查询,合并排除条件 $tax_query = $q->get( 'tax_query' ); $tax_query = $tax_query ?: array(); $tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => 'coin-des-creatrices', 'operator' => 'NOT IN', ); $q->set( 'tax_query', $tax_query ); } } add_action( 'pre_get_posts', 'filtrer_produit_sans_crea' );
额外注意事项
- 确保Post Blocks Adv设置中选择「显示当前归档页」,钩子才能正确作用于当前页面查询
- 修改后清除WordPress缓存和Elementor缓存,避免旧查询缓存导致修改不生效
内容的提问来源于stack exchange,提问作者K-lol
相关产品推荐
相关产品推荐

