Set and display a custom product variation value dynamically on WooCommerce single products Set and display a custom product variation value dynamically on WooCommerce single products wordpress wordpress

Set and display a custom product variation value dynamically on WooCommerce single products


You are making things more complicated that they should be…

Here is a lightweight and effective way to add specific selected variation custom value (from specific product attribute) to an additional html '' after single product meta.

You just need to define the correct product attribute taxonomy in the first function.

The code:

// Add custom variation data to variation form dataadd_filter( 'woocommerce_available_variation', 'add_variation_vendor_value', 10, 3 );function add_variation_vendor_value( $data, $product, $variation ) {    // Here define the targeted taxonomy used in product variation    $taxonomy  = 'pa_mats';    $term_name = $variation->get_attribute($taxonomy);    if( ! empty($term_name) ) {        $data['vendor_value'] = $term_name;    }    return $data;}// Display after product meta an empty span html on variable products add_action( 'woocommerce_product_meta_end', 'display_product_vendors', 10 );function display_product_vendors() {    global $product;    if ( $product->get_type() === 'variable' ) {        echo '<span class="posted_in vendors"></span>';    }}// Fill in our html "span" with specific text value from selected variationadd_action('woocommerce_after_variations_form', 'custom_product_variation_js');function custom_product_variation_js() {    ?>    <script type="text/javascript">    jQuery(function($) {        var $form   = $('form.variations_form'),            $vendor = $('span.vendors'),            text    = $vendor.text();        $form.on('show_variation', function(event, data){ // On selected variation            if ( data.vendor_value ) {                $vendor.text( data.vendor_value );            }        }).on('hide_variation', function(){ // Not on selected variation            $vendor.text( text );        });    });    </script>    <?php}

Code goes in functions.php file of the active child theme (or active theme).

Tested and works on last WooCommerce version (4.9.2) on a variable product with a defined product attribute (for variations) taxonomy.

Remember that product attribute taxonomy always start with "pa_" + product attribute slug.