'Display the selected WooCommerce variation formatted price with shortcode

I have created this piece of code that displays the price on any page on the website, which is controlled by woocommerce.

add_shortcode( 'hhs_product_price', 'hhs_woo_product_price_shortcode' );

function hhs_woo_product_price_shortcode( $atts ) {

    $atts = shortcode_atts( array(

        'id' => null

    ), $atts, 'hhs_product_price' );
 

    if ( empty( $atts[ 'id' ] ) ) {

        return '';

    }

    $product = wc_get_product( $atts['id'] );

    if ( ! $product ) {

        return '';

    }

    return $product->get_price_html();
} 

What I would like to do is modify the code so that if a customer selects a product with a variation. Then the price changes to display the variation price. For example right now if a person selects a product, in this case a tincture bottle, with a price variation connected to the size of the bottle. On the products page they see the following:-

Product (Tincture) $30 - $50

From a drop down menu they can select an option of either 10mg bottle ($30), 15mg bottle ($40), or 20mg bottle ($50). So if a person selects option 20mg the price should display $50 instead of $30 - $50

I have already looked at various posts on stackoverflow with a similar problem but non of those solutions are working for me

Any help would be greatly appropriated.

Thank you



Solution 1:[1]

I'd like to thank LoicTheAztec for this code which is tested and works. However I banged my head on one issue: if product variations are all with the same price, the price_html will come back empty (issue described here: https://github.com/woocommerce/woocommerce/issues/11827). I solved this with a filter found in the github conv above:

add_filter( 'woocommerce_show_variation_price', '__return_true');

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Gabriela Ghiuta