I want to access the selected product variation Weight value in php. I tried below code its getting last value of attribute, not selected.
foreach($product->get_available_variations() as $values){ $weight = $values['attributes']["attribute_weight"]; }
Advertisement
Answer
The selected variation properties can only be accessed via Javascript as it’s a client side live event… Here below is an example, that will display the selected variation custom attribute “attribute_weight” term slug for the variable product, below add to cart button:
add_action( 'woocommerce_after_add_to_cart_form', 'display_selected_variation_data'); function display_selected_variation_data() { global $product; ## For variable products (and their variations) if( $product->is_type('variable') ) { // Here below set your custom attribute name $attribute_name = 'attribute_weight'; // Or "attribute_pa_weight" for non custom attributes ?> <p class="custom-<?php echo $attribute_name; ?>" style="border:solid 1px black; text-align:center"></div> <script type="text/javascript"> jQuery( function($){ // On select variation event $('form.variations_form').on('show_variation', function( event, data ){ var attrValue = data.attributes.<?php echo $attribute_name; ?>; $( 'p.custom-<?php echo $attribute_name; ?>' ).html( data.attributes.<?php echo $attribute_name; ?> );; // For testing (displayed on the browser's console) console.log( 'Variation Id: ' + data.variation_id + ' | Attribute value: ' + attrValue ); }); // On unselect variation event $('form.variations_form').on('hide_variation', function(){ $( 'p.custom-<?php echo $attribute_name; ?>' ).html( '<em>no value</em>' ); }); }); </script><?php } }
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Related: Get currently selected variation id from Woocommerce variable product