在 Woocommerce 中使用 jQuery 产品变体属性进行渲染

问题描述 投票:0回答:2

我正在构建 woocommerce 网上商店,我需要在单个产品页面中显示每个产品的属性。我被各种产品困住了。

虽然我能够在控制台上获取当前的变体属性,但我找不到在页面上打印这些属性的值的方法。

我在 woocommerce 中的short-description.php 文件中使用了此脚本。

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

请问有什么帮助吗?

javascript php jquery wordpress woocommerce
2个回答
2
投票

使用类似于 PHP foreach 循环的 jQuery

each()
函数尝试以下操作...我已将代码嵌入到挂钩函数中,这将使显示无需更改模板(仅用于测试):

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
}

代码位于活动子主题(或活动主题)的 function.php 文件中。已测试并有效。


0
投票

响应 @LoicTheAztec

variation.attributes
会导致未定义的错误。相反,放入
data.attributes
,解决方案就能完美运行。

© www.soinside.com 2019 - 2024. All rights reserved.