2

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

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

1 回答 1

1

选定的变体属性只能通过 Javascript 访问,因为它是客户端实时事件……下面是一个示例,它将显示变量产品的选定变体自定义属性“attribute_weight”术语 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 文件中。测试和工作。

相关:从 Woocommerce 变量产品中获取当前选择的变体 ID

于 2020-10-31T14:09:12.147 回答