WooCommerce Products attribute overwrites over older attributes when saved
-
public static function create_variable_product(){ $variant_data = wp_clean(isset($_POST['data']) ? wp_unslash($_POST['data']) : ''); $product_id = wp_clean(isset($_POST['product_id']) ? wp_unslash($_POST['product_id']) : ''); $product = wc_get_product($product_id); if($product->has_child() == false){ $product = new WC_Product_Variable($product_id); } $attribute = self::create_product_attribute($product,$variant_data); wp_send_json($attribute); } public static function create_product_attribute($product,$variant_data){ $id = []; for($i=0; $i<count($variant_data); $i++){ $attribute = new WC_Product_Attribute(); $attribute->set_id(0); foreach($variant_data[$i] as $key => $value){ if($key == 'attribute_name'){ $attribute->set_name($value); } if($key == 'options'){ $attribute->set_options($value); } } $attribute->set_position( 1 ); $attribute->set_visible( 1 ); $attribute->set_variation( 1 ); $attribute->is_taxonomy(0); $product->set_attributes(array($attribute)); array_push($id,$product->save()); } return $id; }
The data being passed in $_POST[‘data’] is
[{ attribute_name: 'Color', options: ['red','yellow','blue'] }]
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘WooCommerce Products attribute overwrites over older attributes when saved’ is closed to new replies.