如何在 WooCommerce 中获取当前选定的可变产品特定数据

How to get current selected variable product specific data in WooCommerce

我想访问 php 中选定的产品变体权重值。我尝试在下面的代码中获取属性的最后一个值,但未选择。

foreach($product->get_available_variations() as $values){
    $weight = $values['attributes']["attribute_weight"];
}

所选的变体属性只能通过 Javascript 访问,因为它是客户端实时事件……下面是一个示例,它将显示所选的变体自定义属性“attribute_weight” term slug对于变量产品,下面的添加到购物车按钮:

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
    }
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。

相关:Get currently selected variation id from Woocommerce variable product