woocommerce_product_query钩子对Elementor商品标签页不生效问题咨询
WooCommerce Elementor商品标签页分类隐藏失效问题解决方案
失效原因
- Elementor商品组件(含标签页商品模块)采用自定义查询逻辑,默认不会触发WooCommerce原生的
woocommerce_product_query钩子,原有过滤规则无法生效。 - 原有代码存在逻辑错误:将完整的查询参数数组直接赋值给
tax_query字段,会覆盖原有的查询结构,即便是原生WooCommerce查询场景也可能出现异常。
修复方案
方案1:全局查询过滤(适配绝大多数场景)
使用WordPress通用的pre_get_posts钩子,覆盖所有前台商品查询,同时修正原有代码逻辑错误:
// 全局商品分类隐藏规则 function custom_hide_categories_by_location( $q ) { // 仅前台商品查询生效,跳过后台查询、非商品查询 if ( is_admin() || ( ! $q->is_main_query() && ( ! isset( $q->query_vars['post_type'] ) || $q->query_vars['post_type'] !== 'product' ) ) ) { return; } $tempAddress = isset( $_COOKIE["tempAddress"] ) ? $_COOKIE["tempAddress"] : ''; $exclude_category_ids = array( 51, 52, 53 ); // 非纽约地区隐藏指定分类 if ( strpos( $tempAddress, 'New York' ) === false ) { // 保留原有的tax_query规则,避免覆盖其他插件/主题的配置 $existing_tax_query = $q->get( 'tax_query' ) ?: array(); // 新增分类排除规则 $existing_tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $exclude_category_ids, 'operator' => 'NOT IN', ); // 重新赋值tax_query $q->set( 'tax_query', $existing_tax_query ); } } add_action( 'pre_get_posts', 'custom_hide_categories_by_location', 99 );
方案2:额外适配Elementor自定义查询
如果方案1仍有部分Elementor商品模块不生效,可追加Elementor专属的查询过滤钩子:
// 适配Elementor商品查询 add_filter( 'elementor/query/query_args', function( $args, $widget ) { // 仅过滤商品类型查询 if ( ! isset( $args['post_type'] ) || $args['post_type'] !== 'product' ) { return $args; } $tempAddress = isset( $_COOKIE["tempAddress"] ) ? $_COOKIE["tempAddress"] : ''; $exclude_category_ids = array( 51, 52, 53 ); if ( strpos( $tempAddress, 'New York' ) === false ) { $existing_tax_query = isset( $args['tax_query'] ) ? $args['tax_query'] : array(); $existing_tax_query[] = array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $exclude_category_ids, 'operator' => 'NOT IN', ); $args['tax_query'] = $existing_tax_query; } return $args; }, 99, 2 );
内容的提问来源于stack exchange,提问作者Fabio Ricci
相关产品推荐
相关产品推荐

