Change Product Title Based on Variations WooCommerce

Categories: Woocommerce, Wordpress

WooCommerce is an awesome e-commerce plugin that you can use to create beautiful ecommerce stores. However, sometimes you may also need to customise or change its functionalities, based on your customer’s specific requirements. Luckily, WooCommerce is a highly customizable Wordpress plugin. You can use the provided actions to give your clients the best user experience possible. The default WooCommerce behaviour does not allow you to change the page title on the single product page. However, you may want to update the page title, when a new product gallery image is clicked. In this way, the users can more easily understand the differences between the different products. Paste the following code in your child theme’s functions.php file:

<?php
function gcw_insert_captions( $html, $attachment_id ) {
	$captions = '';
	$title = get_post_field( 'post_title', $attachment_id );
	if( !empty( $title ) ) {
		$captions .= '<h2><br>' . esc_html( $title ) . '</h2>';
	}
	$description = get_post_field( 'post_excerpt', $attachment_id );
	if( !empty( $description ) ) {
		$captions .= '<p>' . $description . '</p>';
	}
	if( !empty( $captions ) ) {
		$captions = '<div class="gcw-caption">' . $captions . '</div>';
		
		$html = preg_replace('~<\/div>$~', $captions . '</div>', $html );
	}
	return $html;
}
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'gcw_insert_captions', 10, 2 );
	

The above code gets the image title and prints it just under the main Woocommerce image. To add a title to the image, you need to go to Media -> Library and add your text to your image of choice. After that, you no longer need the original product title. You can hide it with a line of custom css. Place the following css code in theme customiser -> additional css:

.product_title {
display: none;
}

That’s it! Now, the product title of the Wocommerce variable product page will change based on the selected variation image.

Literature: https://github.com/jbeales/woo-gallery-captions

Read more: 12 Custom WooCommerce Functions That Will Make You Stand Out