You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce中通过产品标签正确搜索产品变体?

WooCommerce产品变体标签搜索失效修复方案

问题根源分析

  1. 产品变体无独立标签:WooCommerce的product_tag分类仅绑定在父产品(product类型)上,产品变体(product_variation)不会继承或拥有自身的标签,直接对变体执行tax_query标签筛选必然失效。
  2. 缺失无标签产品筛选逻辑:未选择任何过敏选项时,代码未实现“搜索无标签产品”的需求。
  3. 查询方向错误:原代码直接查询变体,无法关联父产品的标签属性。

修复后的完整代码

<?php
// Input data validation
$survey_data = isset($_POST['survey_data']) ? $_POST['survey_data'] : [];
if (empty($survey_data)) {
    wp_send_json_error('No data provided.');
}

$dog_weight = isset($survey_data['dog_weight']) ? floatval($survey_data['dog_weight']) : 0;
if ($dog_weight <= 0) {
    wp_send_json_error('Invalid dog weight.');
}

// Selecting the product variant based on the dog's weight
$variant_weight = '';
if ($dog_weight >= 1 && $dog_weight <= 4) {
    $variant_weight = '150g';
} elseif ($dog_weight > 4 && $dog_weight <= 8) {
    $variant_weight = '200g';
} elseif ($dog_weight > 8 && $dog_weight <= 15) {
    $variant_weight = '300g';
} elseif ($dog_weight > 15 && $dog_weight <= 24) {
    $variant_weight = '400g';
} elseif ($dog_weight > 24 && $dog_weight <= 35) {
    $variant_weight = '500g';
} elseif ($dog_weight > 35) {
    wp_send_json_error('No products matching the criteria.');
}

// Preparing parent product query (with tag filters)
$parent_args = [
    'post_type' => 'product',
    'posts_per_page' => 6, // 修正注释与代码不一致的问题
    'post_status' => 'publish',
    'tax_query' => [],
];

// Handle tag filtering logic
$allergy_map = [
    'dog_allergy_milk' => 'contains-dairy',
    'dog_allergy_gluten' => 'contains-gluten',
    'dog_allergy_lactose' => 'contains-lactose',
    'dog_allergy_poultry' => 'contains-poultry',
    'dog_allergy_pork' => 'contains-pork',
    'dog_allergy_beef' => 'contains-beef',
    'dog_allergy_horseflesh' => 'contains-horsemeat',
    'dog_allergy_venison' => 'contains-venison',
    'dog_allergy_rabbit' => 'contains-rabbit',
    'dog_allergy_boar' => 'contains-boar'
];

if (!empty($survey_data['dog_allergies'])) {
    // 多个过敏选项同时满足:必须包含所有对应标签
    $parent_args['tax_query']['relation'] = 'AND';
    foreach ($survey_data['dog_allergies'] as $allergy) {
        if (isset($allergy_map[$allergy])) {
            $parent_args['tax_query'][] = [
                'taxonomy' => 'product_tag',
                'field' => 'slug',
                'terms' => $allergy_map[$allergy],
                'operator' => 'IN',
            ];
        }
    }
} else {
    // 未选择任何选项:筛选无product_tag的产品
    $parent_args['tax_query'][] = [
        'taxonomy' => 'product_tag',
        'operator' => 'NOT EXISTS',
    ];
}

// Execute parent product query
$parent_query = new WP_Query($parent_args);
$products = [];

if ($parent_query->have_posts()) {
    while ($parent_query->have_posts()) {
        $parent_query->the_post();
        $parent_product = wc_get_product(get_the_ID());
        
        // Skip non-variable products
        if (!$parent_product->is_type('variable')) {
            continue;
        }
        
        // Find matching variant by weight
        $matching_variant = null;
        foreach ($parent_product->get_available_variations() as $variation) {
            if ($variation['attributes']['attribute_pa_gramatura'] === $variant_weight) {
                $matching_variant = wc_get_product($variation['variation_id']);
                break;
            }
        }
        
        if (!$matching_variant) {
            continue;
        }
        
        // Get product image
        $image_url = '';
        if (has_post_thumbnail($parent_product->get_id())) {
            $image_url = get_the_post_thumbnail_url($parent_product->get_id(), 'medium');
        } elseif (has_post_thumbnail($matching_variant->get_id())) {
            $image_url = get_the_post_thumbnail_url($matching_variant->get_id(), 'medium');
        } else {
            $image_url = wp_get_attachment_url(8448);
        }
        
        $products[] = [
            'title' => $parent_product->get_name(),
            'description' => $parent_product->get_short_description(),
            'image' => $image_url,
            'price' => $matching_variant->get_price(),
            'url' => get_permalink($parent_product->get_id()),
            'gramatura' => $variant_weight,
        ];
    }
    wp_reset_postdata();
    
    if (!empty($products)) {
        wp_send_json_success($products);
    } else {
        wp_send_json_error('No products matching the criteria.');
    }
} else {
    wp_send_json_error('No products matching the criteria.');
}

wp_die();
?>

关键修改说明

  1. 切换查询对象为父产品:先通过product类型查询符合标签条件的父产品,再从中筛选对应重量的变体。
  2. 补充无标签产品筛选:未选择过敏选项时,添加NOT EXISTS的tax_query条件,筛选没有任何product_tag的父产品。
  3. 修正变体匹配逻辑:遍历父产品的可用变体,通过attribute_pa_gramatura属性匹配目标重量的变体。
  4. 统一产品数据获取:从父产品获取标题、描述,变体获取价格,确保数据逻辑一致。
  5. 修正posts_per_page值:将原代码中的1改为注释对应的6,匹配需求。

内容的提问来源于stack exchange,提问作者DMK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 11:50:56