'Display custom stock message for each variation in WooCommerce

Used @7uc1f3r code from this topic. It works great but I would like to do the same but for each variation stock. Because this code get stock from the product page and not from each variation.

I tried with the code below but can't manage to make the text appear only when the variation is selected, and to not display every stock from every variation at once. You can see my problem here.

My code :

add_action( 'woocommerce_after_add_to_cart_form', 'change_stock_message', 5 );
function change_stock_message( $product ) {
    global $product;

     foreach ( $product->get_visible_children() as $variation_id ) {

     $get_product_variation = wc_get_product( $variation_id );

     $product_variation_stock = $get_product_variation->get_stock_status();

        switch ( $product_variation_stock ) {
            case 'instock':
                echo 'In stock';
                break;
            case 'outofstock':
                echo 'Out of stock';
                break;
            case 'onbackorder':
                echo 'On backorder';
                break;
        }
    }
}

What can I add to the code to display stock status text one time only when variation is selected ?

Important : I am not using filter "woocommerce_get_availability_text" but "woocommerce_after_add_to_cart_form".

Thanks for your help !



Sources

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

Source: Stack Overflow

Solution Source