Attributes and variations don’t appear on the edit product page
-
Hello! I’m trying to create attributes and variations programmatically in WooCommerce and having an issue I don’t know how to resolve. I use the code that adds a local attribute ‘Color’ with the value ‘Red’ and creates a variation based on that value. When I click ‘Publish’ on a new product/post, nothing appears in the ‘Attributes’ and ‘Variations’ tabs on the editing page. However, on the client side, on the product page, both the color and the option ‘Red’ appear and in database I can see them too.
Here’s the interesting part – afterward, no matter how many times I click the ‘Update’ button for the product/post, nothing appears on the editing page. But as soon as I refresh the page in the BROWSER (not the post refresh button, but refreshing the browser content), everything appears on the product editing page in the ‘Attributes’ and ‘Variations’ tabs and the number of variations equals the number of times I updated the product. Also, the values for the variations are not set; I have to set them manually.
I don’t understand what the issue is and desperately need help. Please help me resolve this problem? Here is the code I use:
$color = 'Red'; $taxonomy = 'color'; $attribute = new WC_Product_Attribute(); $attribute->set_name('Color'); $attribute->set_options(array( $color, )); $attribute->set_position(1); $attribute->set_visible(1); $attribute->set_variation(1); $product = wc_get_product($product_id); $product->set_attributes(array($attribute)); $product->save(); $attribute_term = get_term_by('name', $color, $taxonomy); $variation = new WC_Product_Variation(); $variation->set_sku('yourSku_' . time()); $variation->set_regular_price(127); $variation->set_parent_id($product_id); $variation->set_weight('50g'); $variation->set_attributes(array($taxonomy => $attribute_term->term_id)); $variation->set_status('publish'); $variation->save(); $product->save(); //echo the data $variation_data = $variation->get_data(); echo '<pre>'; print_r($variation_data); echo '</pre>';
- The topic ‘Attributes and variations don’t appear on the edit product page’ is closed to new replies.