根据变体更改WooCommerce可变产品标题?

问题描述

请帮助获取WooCommerce可变产品标题,以根据口味和尺寸进行更改。我希望在选择口味和大小时更改标题,例如“产品名称-Chocolate-5lbs”。

Photo

下面的代码适用于一个属性

add_filter( 'wp_footer','custom_product_title_script' );

函数custom_product_title_script(){ 全球$ post;

// Only single product pages
if( ! is_product() ) return;

// get an instance of the WC_Product Object
$product = wc_get_product($post->ID);

// Only for variable products
if( ! $product->is_type( 'variable' ) ) return;

// Here set your specific product attributes in this array (coma separated):
$attributes = array('pa_flavor');

// The 1st loop for variations IDs
foreach($product->get_visible_children( ) as $variation_id ) {

    // The 2nd loop for attribute(s)/value
    foreach($product->get_available_variation( $variation_id )['attributes'] as $key => $value_id ){
        $taxonomy = str_replace( 'attribute_','',$key ); // Get the taxonomy of the product attribute

        // Just for defined attributes
        if( in_array( $taxonomy,$attributes) ){
            // Set and structure data in an array( variation ID => product attribute => term name )
            $data[ $variation_id ][$taxonomy] = get_term_by( 'slug',$value_id,$taxonomy )->name;
        }
    }
}

?>
    <script type="text/javascript">
        (function($){
            // variables initialization
            var variationsData = <?PHP echo json_encode($data); ?>,productTitle = $('.product_title').text(),flavor = 'pa_flavor';
            console.log(variationsData);

            // function that get the selected variation and change title
            function update_the_title( productTitle,variationsData,flavor ){
                $.each( variationsData,function( index,value ){
                    if( index == $('input.variation_id').val() ){
                        $('.product_title').text(productTitle+' - '+value[flavor]);
                        console.log('TITLE UPDATED');
                        return false;
                    } else {
                        $('.product_title').text(productTitle);
                    }
                });
            }

            // Once all loaded
            setTimeout(function(){
                update_the_title( productTitle,flavor );
            },300);

            // On live event: select fields
            $('select').blur( function(){
                update_the_title( productTitle,flavor );
            });
        })(jQuery);
    </script>
<?PHP

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)