J__
J__

Reputation: 86

Render with jQuery product variation attributes in Woocommerce

I am building a woocommerce eshop and i need to show the attributes of each product in the single product page. I got stuck on the variable products.

While I am able to get the current variation attributes on the console, I cant find a way to print the values of these attributes on the page.

I used this script at the short-description.php file in woocommerce.

 <script>
    jQuery(document).ready(function( $ ){
    $( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {
    $('#variation_descr').html(variation.variation_description);
    console.log (variation.attributes);

    } );
        });
    </script>

Any help please?

Upvotes: 1

Views: 2421

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

Try the following using jQuery each() function that is similar to a PHP foreach loop… I have embedded the code in a hooked function, that will make the display without any need of changing templates (just for testing):

add_action( 'woocommerce_before_single_variation', 'custom_before_single_variation' );
function custom_before_single_variation() {
    ?>
    <div id="variation_descr"></div>
    <script>
        jQuery(function($){
            $(".single_variation_wrap" ).on( "show_variation", function ( event, data ) {
                $('#variation_descr').html(data.variation_description);
                
                $.each(variation.attributes, function(attribute,value){
                    $('#variation_descr').append('<p><strong>'+attribute+'</strong>: '+value+'</p>');
                    console.log("Attribute: "+attribute+" | Value: "+value);
                });
                console.log("Variation Id: "+data.variation_id);
            });
        });
    </script>
    <?php
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Upvotes: 2

Related Questions