This is starting to give me a headache so hope someone here can help me and together we can help others with the same problem!
I built a plugin which generates product variations for WooCommerce automatically. This all seems to work fine except for one thing. New variations are not visible in the frontend and when I look at the product edit page they are listed like this:
When I hit the Update button and save the product, it gets magically fixed. Variations are visible in the frontend and in the back they look like this now:
The code
// Get the Variable product object (parent)
$product = wc_get_product($parent_id);
$variation_post = array(
'post_title' => $product->get_title(),
'post_name' => 'product-'.$parent_id.'-variation',
'post_status' => ($enable_variations == "yes") ? 'publish' : 'private',
'post_parent' => $parent_id,
'post_type' => 'product_variation',
'guid' => $product->get_permalink()
);
// Creating the product variation
$variation_id = wp_insert_post( $variation_post, true );
$fields = array(
'_manage_stock' => 'yes',
'_backorders' => $backorders,
'_stock_status' => $stock_status,
'_stock' => $stock,
'_regular_price' => $price,
'_price' => $price,
);
foreach ( $fields as $meta_key => $meta_value ) {
update_post_meta($variation_id, $meta_key, $meta_value);
}
// Add attribute 1 to variation
wp_set_post_terms( $variation_id, sanitize_title($attribute_value), "pa_attribute_1", true );
update_post_meta( $variation_id, 'attribute_pa_attribute_1', sanitize_title($attribute_value));
// Add attribute 2 to variation
wp_set_post_terms( $variation_id, sanitize_title($attribute_value), "pa_attribute_2", true );
update_post_meta( $variation_id, 'attribute_pa_attribute_2', sanitize_title($attribute_value));
// Add attribute 3 to variation
wp_set_post_terms( $variation_id, sanitize_title($attribute_value), "pa_attribute_3", true );
update_post_meta( $variation_id, 'attribute_pa_attribute_3', sanitize_title($attribute_value));
wc_delete_product_transients($variation_id);
What am I missing? What happens when you click Update at a product? Already tried to use $product->save() and deleting transients like answered in most topics on the web.