Dynamically show WooCommerce variation info with JavaScript

/**
 * Dynamically shows variation weight.
 *
 * @see https://wpcodebook.com/woocommerce-dynamically-show-variation-info-javascript/
 */
add_action( 'wp_head', function () {
	?>
	<script>
		jQuery( document ).ready( function () {

			// Add placeholder
			jQuery( '.variations_form' ).closest( '.single-product' ).find( '.product_meta' ).
				append( '<span class="wpcodebook_weight_wrapper">Weight: <span class="wpcodebook_weight">N/A</span></span>' );

			// Display variation weight
			jQuery( '.variations_form' ).on( 'found_variation', function ( event, variation ) {
				jQuery( this ).closest( '.single-product' ).find( '.product_meta .wpcodebook_weight' ).
					text( variation.weight + ' kg' );
			} );

			// Reset
			jQuery( '.variations_form' ).on( 'reset_data', function ( event ) {
				jQuery( this ).closest( '.single-product' ).find( '.product_meta .wpcodebook_weight' ).
					text( 'N/A' );
			} );

		} );
	</script>
	<?php
} );

Leave a Comment