'Issue in Wordpress programmatically created product filter on shop page

I am creating products in WordPress programmatically. Everything seems ok but the shop page filter by attribute name is not working with these products.

enter image description here

If we open these products in wp-admin and save attributes then it is working.

enter image description here

I am not sure what is the issue.

function addAttributes($product_id, $attributes){
    $product_attributes = array();
    foreach( $attributes as $key => $terms ){
        
        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
        $attr_label = ucfirst($key); // attribute label name
        $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
        // NEW Attributes: Register and save them
        if( ! taxonomy_exists( $taxonomy ) ){
            $crRes = save_product_attribute_from_name( $attr_name, $attr_label );
        }
            

        $product_attributes[$taxonomy] = array (
            'name'         => $taxonomy,
            'value'        => '',
            'position'     => '',
            'is_visible'   => 1,
            'is_variation' => 0,
            'is_taxonomy'  => 1
        );

        
        //foreach( $terms as $value ){
            echo "value >>>"; print_r($terms);
            if(empty($terms)) continue;
            $term_name = ucfirst($terms);
            $term_slug = sanitize_title($terms);

            // Check if the Term name exist and if not we create it.
            if( ! term_exists( $terms, $taxonomy ) )
                wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
           
            // Set attribute values
            echo  "product_id ".$product_id." ; term_name ".$term_name." ; taxonomy ".$taxonomy;
            $upRes = wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
            echo "upRes";
       
    }
    update_post_meta( $product_id, '_product_attributes', $product_attributes );
    $product = new WC_Product_Variable( $product_id );
    $product->save();

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source