I think the condition here has_term($term_slug, $taxonomy, $variation->get_id())
won’t work for variation. If you want to check term, we need to check with parent variable product instead of checking variation because Woocommerce doesn’t store any taxonomy/term attribute to variation.
Instead of using has_term
, we can use your existing attributes in get_variation_attributes
to get and check condition because a variable product may have defined taxonomy as attribute or custom attribute defined directly in Attributes tab. As you can see in my screenshot below:
So I updated your code to make the data-variation-id
work properly
if($product->is_type('variable')) :
$available_variations = $product->get_children();
if($attributes = $product->get_variation_attributes()){
foreach($attributes as $attribute_name => $options) :
$taxonomy = str_replace('attribute_', '', $attribute_name);
$attribute_label = wc_attribute_label($taxonomy);
echo '<label for="' . esc_attr($taxonomy) . '">' . esc_html($attribute_label) . '</label>';
echo '<select name="' . esc_attr($taxonomy) . '" id="' . esc_attr($taxonomy) . '">';
$variation_ids_map = [];
foreach($options as $option_slug) :
$current_variation_id = '';
$term = get_term_by('slug', $option_slug, $taxonomy);
$term_name = $term ? $term->name : $option_slug; // for custom attribute
foreach($available_variations as $variation_id_candidate) :
$variation = wc_get_product($variation_id_candidate);
if($variation && $variation->attributes[$taxonomy] == $option_slug) :
$current_variation_id = $variation->get_id();
break;
endif;
endforeach;
$variation_ids_map[$option_slug] = $current_variation_id;
echo '<option value="' . esc_attr($option_slug) . '" data-variation-id="' . esc_attr($current_variation_id) . '">' . esc_html($term_name) . '</option>';
endforeach;
echo '</select>';
endforeach;
}
endif;