Woocommerce,在产品标题后显示选定的属性标题

Woocommerce, show selected attribute title after a product title

我发现这段代码在标题后显示属性:

    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
    global $product;

    $brand_name = $product->get_attribute('brand-name');

    echo '<h1 class="product_title entry-title">';
    the_title();
    if( $brand_name )
        echo ' - ' . $brand_name;
    echo '</h1>';
}

可行,但我尝试只显示一个选定的属性。

来自颜色的示例属性:白色和黑色

代码的工作方式类似于

"Product Title - White, Color"

我要展示的是

如果没有选择任何属性

"Product Title"(not to appear anything)

如果选择白色,显示喜欢

"Product Title - White"

在您的 functions.php 中添加代码。将 pa_color 替换为您的属性

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_single_product_summary', 'custom_template_single_title', 5 );
function custom_template_single_title() {
   global $product;

   $brand_name = $product->get_attribute('brand-name');
   $brand_output = '';
   if( $brand_name )
       $brand_output = ' - ' . $brand_name;

   echo sprintf('<h1 class="product_title entry-title">%s %s <span></span></h1>',get_the_title(),$brand_output);
}

function change_title_on_color_change() { 
    global $product;
    if($product->get_type() !== 'variable') return;    
?>
<script>
jQuery(function($) {

    $(document).ready(function() {
        update_product_title();
    });
    $('select#pa_color').change( function(){
        update_product_title();
    });
    function update_product_title() {
        var color_val = $('select#pa_color option').filter(':selected').val();
        var color_text = $('select#pa_color option').filter(':selected').text();
        if(color_val.length > 0) {
            $('.product_title.entry-title span').text(' - ' + color_text);
        } else {
            $('.product_title.entry-title span').empty();
        }
    }
});
</script>
<?php
}
add_action('woocommerce_after_single_product','change_title_on_color_change');