הרבה פעמים יש צורך להוסיף תכונה, וזה ממש בעייתי אחרי שכבר יש תכונות, כי הטעינה מקובץ דורסת את כל התכונות.
הקוד המצורף מטפל בבעיה.
כמובן יש לשמור ב funciton.php של התבנית
add_action( 'init', 'create_new_taxonomy' );
function create_new_taxonomy()
{
if ($_GET['load_attr']) {
global $woocommerce;
$attr_tax = wc_get_attribute_taxonomies();
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM manufactures");
foreach ($results as $row) {
$id = $row->COL1;
//$attr_slug = 'man';
$term_name = $row->COL2;
$taxonomy = 'pa_man'; // The taxonomy
$term_slug = sanitize_title($term_name); // The term "slug"
// Check if the term exist and if not it create it (and get the term ID).
if (!term_exists($term_name, $taxonomy)) {
$term_data = wp_insert_term($term_name, $taxonomy);
$term_id = $term_data['term_id'];
} else {
$term_id = get_term_by('name', $term_name, $taxonomy)->term_id;
}
// get an instance of the WC_Product Object
$product = wc_get_product( $id );
$attributes = (array) $product->get_attributes();
// 1. If the product attribute is set for the product
if( array_key_exists( $taxonomy, $attributes ) ) {
foreach( $attributes as $key => $attribute ){
if( $key == $taxonomy ){
$options = (array) $attribute->get_options();
$options[] = $term_id;
$attribute->set_options($options);
$attributes[$key] = $attribute;
break;
}
}
$product->set_attributes( $attributes );
}
// 2. The product attribute is not set for the product
else {
$attribute = new WC_Product_Attribute();
$attribute->set_id( sizeof( $attributes) + 1 );
$attribute->set_name( $taxonomy );
$attribute->set_options( array( $term_id ) );
$attribute->set_position( sizeof( $attributes) + 1 );
$attribute->set_visible( true );
$attribute->set_variation( false );
$attributes[] = $attribute;
$product->set_attributes( $attributes );
}
$product->save();
// Append the new term in the product
if( ! has_term( $term_name, $taxonomy, $id ))
wp_set_object_terms($id, $term_slug, $taxonomy, true );
}
}
}