WooCommerce产品搜索无法按product_tag检索,是否与现有搜索代码冲突?
问题原因
- 核心语法错误:你当前使用的按标签搜索代码存在逻辑错误,
meta_query仅用于查询自定义字段,无法查询product_tag这类分类法,需要替换为tax_query参数才能正确匹配产品标签。 - 钩子执行冲突:按SKU搜索和按标签搜索的两个函数都挂载在
posts_search钩子下,且优先级均为999,后执行的函数会覆盖前一个函数对搜索SQL的修改结果,导致其中一个功能失效。 - 字符串替换逻辑冲突:两个函数都使用相同的字符串替换规则修改SQL,连续执行会导致SQL结构异常,查询出错。
解决方法
首先删除原有三个代码片段,替换为下方整合后的代码即可同时支持按产品标签、SKU搜索,且自动限制搜索范围为产品:
// 限制前端搜索仅查询产品,设置搜索分页数量 add_filter('pre_get_posts','custom_search_filter'); function custom_search_filter($query) { if ($query->is_search && !is_admin() ) { $query->set('post_type',array('product')); $query->set('posts_per_page',12); } return $query; } // 整合SKU、产品标签搜索逻辑 add_filter( 'posts_search', 'custom_product_search', 999, 2 ); function custom_product_search( $search, $query_vars ) { global $wpdb, $pagenow; // 后台编辑页、无搜索关键词时直接返回原搜索条件 if ( 'edit.php' == $pagenow || empty($search) || empty($query_vars->query['s']) ) { return $search; } $keyword = $query_vars->query['s']; $matched_ids = array(); // 1. 查询匹配SKU的产品 $sku_args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_sku', 'value' => $keyword, 'compare' => 'LIKE' ) ) ); $sku_matched = get_posts($sku_args); if (!empty($sku_matched)) { $matched_ids = array_merge($matched_ids, $sku_matched); } // 2. 查询匹配产品标签的产品 $tag_args = array( 'posts_per_page' => -1, 'post_type' => 'product', 'fields' => 'ids', 'tax_query' => array( array( 'taxonomy' => 'product_tag', 'field' => 'name', 'terms' => $keyword, 'compare' => 'LIKE', ) ) ); $tag_matched = get_posts($tag_args); if (!empty($tag_matched)) { $matched_ids = array_merge($matched_ids, $tag_matched); } // 有匹配结果则修改搜索SQL $matched_ids = array_unique($matched_ids); if ( !empty($matched_ids) ) { $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $matched_ids ) . ")) OR (", $search); } return $search; }
生效验证
代码添加完成后清空站点缓存,输入产品标签或者SKU关键词测试即可,两个搜索能力可同时生效互不干扰。
内容的提问来源于stack exchange,提问作者steven_leek_glevents
相关产品推荐
相关产品推荐

