Home > Mobile >  Woocommerce, show selected attribute title after a product title
Woocommerce, show selected attribute title after a product title

Time:11-08

I found this code to show attribute after a title: Add specific product attribute after title on Woocommerce single products

    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 >';
    the_title();
    if( $brand_name )
        echo ' - ' . $brand_name;
    echo '</h1>';
}

is work but, i try to show only one the selected attribute to appear.

An example attribute from color: white and black

The code works like

"Product Title - White, Color"

What i want to show is

if not selected any attribute

"Product Title"(not to appear anything)

if selected white, show like

"Product Title - White"

CodePudding user response:

Add the code in your functions.php . Replace pa_color with your attribute

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 >%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');
  • Related