5

I'm looking for some help getting the WooCommerce variable product title to change based on variations. In this specific case I would like the title to change when a color is selected, like "Productname Black".

Is there any easy snippet to get this to work?

4

1 回答 1

12

更新04-2021 - 在 WooCommerce 5.1+ 上成功测试(处理自定义产品属性)

以下代码将根据特定定义的产品属性(或所有这些属性可选)将所选变体的值添加到变量产品标题中:

编码:

// Defining product Attributes term names to be displayed on variable product title
add_filter( 'woocommerce_available_variation', 'filter_available_variation_attributes', 10, 3 );
function filter_available_variation_attributes( $data, $product, $variation ){
    // Here define the product attribute(s) slug(s) which values will be added to the product title
    // Or replace the array with 'all' string to display all attribute values
    $attribute_names = array('Custom', 'Color');

    foreach( $data['attributes'] as $attribute => $value ) {
        $attribute      = str_replace('attribute_', '', $attribute);
        $attribute_name = wc_attribute_label($attribute, $variation);

        if ( ( is_array($attribute_names) && in_array($attribute_name, $attribute_names) ) || $attribute_names === 'all' ) {
            $value = taxonomy_exists($attribute) ? get_term_by( 'slug', $value, $attribute )->name : $value;

            $data['for_title'][$attribute_name] = $value;
        }
    }
    return $data;
}

// Display to variable product title, defined product Attributes term names
add_action( 'woocommerce_after_variations_form', 'add_variation_attribute_on_product_title' );
function add_variation_attribute_on_product_title(){
    // Here define the separator string
    $separator = ' - ';
    ?>
    <script type="text/javascript">
    (function($){
        var name = '<?php global $product; echo $product->get_name(); ?>';

        $('form.cart').on('show_variation', function(event, data) {
            var text = '';

            $.each( data.for_title, function( key, value ) {
                text += '<?php echo $separator; ?>' + value;
            });

            $('.product_title').text( name + text );

        }).on('hide_variation', function(event, data) {
            $('.product_title').text( name );
        });
    })(jQuery);
    </script>
    <?php
}

显示所有属性

$attribute_names您可以通过将变量定义为如下所示显示所选变体的所有变体属性值"all"

$attribute_names = "all";

代码在您的活动子主题(或主题)的functions.php 文件中或任何插件文件中。

经过测试并且可以工作......你会得到类似的东西:

在此处输入图像描述

于 2017-11-25T01:19:40.443 回答