Home  >  Q&A  >  body text

Woocommerce dynamically changes price of variable products once specific variant changes

I wrote this to extract the product change price

global $product;

        if ( $product->is_type('variable') ) {

            function get_product_variation_price($variation_id) {

                global $woocommerce; 
                $product = new WC_Product_Variation($variation_id);
                return $product->get_price_html(); 
                } 
            $product_variations = $product->get_available_variations();
            $arr_variations_id = array();
            foreach ($product_variations as $variation) {
                $product_variation_id = $variation['variation_id'];
                $product_price = get_product_variation_price($product_variation_id);
            }

            $amount = get_product_variation_price($product_variation_id);
         
        } else {
            $amount = str_replace(".", ",", $product->get_price());
        }

What I want to achieve is if the product is a variable product, the amount variable changes to set the price for the currently selected variant, however, this always gives me the first variant price. How can I achieve this?

P粉752290033P粉752290033288 days ago458

reply all(1)I'll reply

  • P粉604507867

    P粉6045078672024-01-29 17:48:31

    I don't see any reason to create a plugin to show changing prices since this is the default setting of woocommerce. Can you share why you created this plugin? Default functionality not working on your site? If you only want to change the decimal places of the price, you can change these settings from the currency options.

    reply
    0
  • Cancelreply