Set Default Product Variation Attribute
Berikut ini adalah contoh code untuk membuat default product attribute variation ketika hanya memiliki satu option pilihan variasi untuk masing-masing attribute yang ada
function get_variation_slug($taxonomy, $term_name)
{
if (term_exists($term_name, $taxonomy)) {
$term_slug = get_term_by('name', $term_name, $taxonomy)->slug;
} else {
$term_slug = '';
}
return $term_slug;
}
global $product;
if (!count($default_attributes = get_post_meta($product->get_id(), '_default_attributes'))) {
$new_defaults = [];
$product_attributes = $product->get_attributes();
if (count($product_attributes)) {
foreach ($product_attributes as $key => $attributes) {
$values = explode(',', $product->get_attribute($key));
if (count($values) == 1 && !isset($default_attributes[$key])) {
$key_val = get_variation_slug($key, $values[0]);
$new_defaults[$key] = $key_val;
}
}
if(count($new_defaults)) {
update_post_meta($product->get_id(), '_default_attributes', $new_defaults);
}
}
}