I want to change the Woocommerce variable product title when someone selects the varient. I want to add the selected variant to title.
I have used this Change WooCommerce variable product title based on variation code It’s working perfectly for attributes that are added from product->attributes .But i want that to work for custom product attributes which we add when adding product.
I tried the code provided in above link for that but it’s not working for custom product attributes.It returns a null value.
colorr is the name of attribue i added using custom product attributes
Here is my code.Any help will be highly appriciated
add_filter( 'wp_footer','custom_product_title_script' );
function custom_product_title_script(){
global $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('colorr');
// 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(),
color = 'colorr';
console.log(variationsData);
// function that get the selected variation and change title
function update_the_title( productTitle, variationsData, color ){
$.each( variationsData, function( index, value ){
if( index == $('input.variation_id').val() ){
$('.product_title').text(productTitle+' - '+value[color]);
console.log('TITLE UPDATED');
return false;
} else {
$('.product_title').text(productTitle);
}
});
}
// Once all loaded
setTimeout(function(){
update_the_title( productTitle, variationsData, color );
}, 300);
// On live event: select fields
$('select').blur( function(){
update_the_title( productTitle, variationsData, color );
});
})(jQuery);
</script>
<?php
}
2
Answers
Not sure why you used php, that’s totally front task – so should be done with front js.
Please add this js to external javascript file (it so bad practice to inject js inline, especially jquery – it will block defer optimization)
How it works:
Solution tested on default twentyseventeen theme.
Ivan Frolov, you have an error in the code, you did not add the letter E add_variation_txt_to_titl(); but you must add_variation_txt_to_title();
Full code :