Skip to content

Instantly share code, notes, and snippets.

@cyberdev
Last active April 28, 2024 06:01
Show Gist options
  • Save cyberdev/3199437e3639a22ff2e22f86debae85f to your computer and use it in GitHub Desktop.
Save cyberdev/3199437e3639a22ff2e22f86debae85f to your computer and use it in GitHub Desktop.
Set Woocommerce Product Attribute
<?php
public function set_product_attribute($taxonomy, $terms, $isvariation = true)
{
$taxonomyName = $this->taxonomy_create($taxonomy);
$terms = explode('|', $terms);
$term_ids = [];
foreach ($terms as $term_name) {
$term_name = mb_substr($term_name, 0, 200);
if (!empty($term_name)) {
$term_slug = sanitize_title($term_name);
if (!term_exists($term_name, $taxonomyName)) {
$term_data = wp_insert_term($term_name, $taxonomyName);
$term_id = $term_data['term_id'];
} else {
$term_id = get_term_by('name', $term_name, $taxonomyName)->term_id;
}
$term_ids[] = $term_id;
}
}
$attribute = new WC_Product_Attribute();
$attribute->set_id(wc_attribute_taxonomy_id_by_name($taxonomyName));
$attribute->set_name($taxonomyName);
$attribute->set_options($term_ids);
//$attribute->set_position(sizeof($attributes) + 1);
$attribute->set_visible(true);
$attribute->set_variation($isvariation);
return $attribute;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment