How to insert variable product with PHP?

When I try to use WC_Product_Variable() the variations are created but somehow not properly synced / assigned. Deleting and creating the variations from /wp-admin/ works but how can I properly add variations to a product with PHP code?

I currently have this:

public static function create_wc_variable_product($products_to_import, $common_items, $variant_name)
    {
        $unique_short_descs = array_unique(array_column($products_to_import, 'short_desc'));

        $product = new WC_Product_Variable();
        $product->set_name($variant_name);
        $product->set_status('publish');
        $product->set_description('Variable Product Description');
        $product->set_short_description('Short Description');

        $attribute = new WC_Product_Attribute();
        $attribute->set_id(0);
        $attribute->set_name('Variation');
        $attribute->set_options($unique_short_descs);
        $attribute->set_position(0);
        $attribute->set_visible(true);
        $attribute->set_variation(true);

        $product->set_attributes([$attribute]);
        $product->set_variation_attributes([$attribute]);
        $product->save();
        $product_id = $product->get_id();

        foreach ($products_to_import as $product_data) {
            $variation = new WC_Product_Variation();
            $variation->set_parent_id($product_id);
            $variation->set_attributes(['Variation' => $product_data['short_desc']]);
            $variation->set_status('publish');
            $variation->set_regular_price(isset($product_data['list_price']) ? $product_data['list_price'] : 0);
            $variation->set_sku(isset($product_data['article_nr']) ? $product_data['article_nr'] : null);
            $variation->save();

            update_post_meta($variation->get_id(), 'hwp_var_gtin', isset($product_data['technical_details']['GTIN']) ? $product_data['technical_details']['GTIN'] : '');
        }
    }

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer