如何为WooCommerce创建过敏原排除式成分搜索分类法
核心逻辑
- 结构化成分数据:把散落在短描述里的成分提取出来,做成WooCommerce产品的自定义分类法,实现精准的成分关联与筛选,避免文本模糊匹配的误差。
- 反向筛选逻辑:修改默认“包含关键词”的搜索逻辑,改为“排除指定分类法项”的查询,同时可兼容未迁移的短描述数据,确保搜索结果完全不含用户禁忌成分。
落地实现方案
一、构建成分自定义分类法
1. 注册分类法
在主题的functions.php中添加以下代码,创建名为“产品成分”的自定义分类法,关联WooCommerce产品:
function register_product_ingredient_taxonomy() { $args = array( 'labels' => array( 'name' => '产品成分', 'singular_name' => '成分', 'search_items' => '搜索成分', 'all_items' => '所有成分', 'edit_item' => '编辑成分', 'update_item' => '更新成分', 'add_new_item' => '添加新成分', 'new_item_name' => '新成分名称', 'menu_name' => '成分管理' ), 'public' => true, 'hierarchical' => false, // 成分按平级管理,无需层级 'show_in_rest' => true, // 支持块编辑器 'show_admin_column' => true, // 在产品列表页显示成分列,方便管理 'rewrite' => array('slug' => 'product-ingredient') ); register_taxonomy('product_ingredient', 'product', $args); } add_action('init', 'register_product_ingredient_taxonomy');
2. 迁移成分数据
- 手动迁移:编辑每个产品,在右侧“产品成分” metabox中勾选对应的成分。
- 批量迁移:如果短描述中成分格式统一(比如用逗号分隔),可以写脚本批量提取并关联,或使用WP All Import等插件批量导入。
二、修改搜索表单添加排除选项
在你的基础搜索表单中,添加成分多选框,让用户选择需要排除的成分:
<div class="search-exclude-ingredients"> <label for="exclude_ingredients">排除禁忌成分:</label> <select name="exclude_ingredients[]" id="exclude_ingredients" multiple> <?php // 获取所有成分分类项 $ingredients = get_terms(array( 'taxonomy' => 'product_ingredient', 'hide_empty' => false )); foreach ($ingredients as $ingredient) { echo '<option value="' . esc_attr($ingredient->slug) . '">' . esc_html($ingredient->name) . '</option>'; } ?> </select> <small>按住Ctrl(Windows)/Cmd(Mac)可多选</small> </div>
三、调整搜索查询实现成分排除
在functions.php中添加以下代码,通过pre_get_posts钩子修改产品搜索的查询逻辑,实现排除指定成分:
function exclude_ingredients_from_product_search($query) { // 仅处理前台产品搜索主查询 if (!is_admin() && $query->is_search() && $query->is_main_query() && $query->get('post_type') === 'product') { $exclude_ingredients = isset($_GET['exclude_ingredients']) ? array_map('sanitize_text_field', $_GET['exclude_ingredients']) : array(); if (!empty($exclude_ingredients)) { // 构建分类法排除查询 $tax_query = $query->get('tax_query') ?: array(); $tax_query[] = array( 'taxonomy' => 'product_ingredient', 'field' => 'slug', 'terms' => $exclude_ingredients, 'operator' => 'NOT IN' ); // 兼容未迁移到分类法的短描述数据(可选) $exclude_pattern = implode('|', array_map('preg_quote', $exclude_ingredients)); $tax_query['relation'] = 'AND'; $tax_query[] = array( 'key' => '_short_description', 'value' => $exclude_pattern, 'compare' => 'NOT REGEXP' ); $query->set('tax_query', $tax_query); } } } add_action('pre_get_posts', 'exclude_ingredients_from_product_search');
四、测试验证
- 给部分产品添加成分分类,比如给A产品添加“牛奶”成分,B产品添加“花生”成分,C产品无特殊成分。
- 搜索时选择排除“牛奶”,检查结果是否只显示B和C。
- 若保留了短描述兼容代码,测试短描述含“牛奶”的产品是否也被排除。
内容的提问来源于stack exchange,提问作者unity-student
相关产品推荐
相关产品推荐

