colapsnux
colapsnux

Reputation: 942

Get variable product price with jQuery in WooCommerce?

I have some variation per products which contain different price, I'm trying to get the product variable price with jQuery and I get it but this code bellow only get the min variation price and I would like to get the current price for the current variation. Then when I change another select value, the variation change in the front end with the correct price, but in the console log the min price is showed again and again and not the corresponding price for the corresponding variation.

jQuery( '.variations_form' ).each( function() {
    // when variation is found, do something
    jQuery(this).on( 'found_variation', function( event, variation ) {
        var product    = '<?php echo wc_get_product($variation_id) ?>',
            price      = <?php echo $product->get_price() ?>;
        console.log(price);
    });
});

I tried to look into the add-to-cart-variation.js and the wp-util.js file to find some way but I 'm not able to do it.

Is there a way to retrieve correctly the current variation price dynamically with jQuery ?

Upvotes: 3

Views: 12030

Answers (2)

Andy
Andy

Reputation: 515

Your code are on the track just use variation to get price, image, etc

jQuery(document).ready(function() {
    jQuery( '.variations_form' ).each( function() {
        jQuery(this).on( 'found_variation', function( event, variation ) {
            console.log(variation);//all details here
            var price = variation.display_price;//selectedprice
            console.log(price);
        });
    });
   });

Upvotes: 6

colapsnux
colapsnux

Reputation: 942

I found a solution but it retrieve the price from the .single_variation_wrap -> .price -> .amount text which is outputed from variation.php file.

jQuery( '.variations_form' ).each( function() {
        jQuery(this).on( 'change', '.variations select', function() {
            var currency    = currency = ' <?php echo get_woocommerce_currency_symbol(); ?>',
                price       = jQuery('.woocommerce-variation-price .amount').text().replace(/ /g,''),
                parsePrice  = parseFloat(price),
                totalPrice  = parsePrice.toFixed(2) + currency;

            if ( jQuery('.single_variation_wrap .test').length ) {
              jQuery('.single_variation_wrap .test').html('');  
            }
            console.log(totalPrice);
            jQuery('.single_variation_wrap').append('<span class="test">' + totalPrice + '</span>');
        });
    });

It's not a pretty well solution but it works.

Is there any other proffesional solution how can I make it ?

Upvotes: 3

Related Questions