【问题标题】:Add some attribute values to WooCommerce variable product title from chosen variation从所选变体向 WooCommerce 变量产品标题添加一些属性值
【发布时间】:2018-05-07 19:39:19
【问题描述】:

我正在寻求一些帮助,让 WooCommerce 变量产品标题根据变化进行更改。在这种特定情况下,我希望在选择颜色时更改标题,例如“Productname Black”。

有什么简单的sn-p可以让它工作吗?

【问题讨论】:

  • 所以你想在每次选择颜色时在产品标题的末尾添加颜色属性值,在单个产品页面上,对吗? …您的网站有实时链接吗?
  • 嗨!对,那是正确的。目前该网站还没有上线,但也许我可以给你一些访问权限,或者有什么简单的方法可以实现这个吗?
  • @LoicTheAztec 我已经加你了,谢谢!

标签: php jquery wordpress woocommerce product-variations


【解决方案1】:

更新 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 文件或任何插件文件中。

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

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 1970-01-01
    • 2019-03-08
    • 2017-01-01
    • 2018-10-11
    • 1970-01-01
    • 2019-01-23
    • 2019-07-29
    • 2019-07-09
    相关资源
    最近更新 更多