D
D
dimitriylutsenko2021-07-09 14:38:59
WordPress
dimitriylutsenko, 2021-07-09 14:38:59

How to display attributes of selected Woocommerce variation?

Hello.

I have a need to populate a "Features" or "Details" table on a Woocommerce product page.
The main problem is that I can't display the attribute values ​​of the selected product variation.
This table simply lists all the attributes involved in variation.
60e8338b25168436691244.png
There are a lot of instructions on the Internet on how to customize the 'woocommerce_available_variation' hook so that the value of the fields of the selected variation is displayed above the "Cart" button with the price.
But I can't name this solution. Since I can have 5-10 attributes (And they can have completely different values, which cannot be written in the main product in the Description)
60e834d585411782957645.png

So how can I implement the ability to display the values ​​of the parameters of the selected variation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dimitriylutsenko, 2021-07-12
@dimitriylutsenko

Oh, as always, I found the solution myself...
I don't know why Woocommerce didn't implement the necessary functionality for displaying the characteristics of the selected variation in the table, without crutches and blue tape anywhere...
Instruction (I developed a minimally working code, I leave it on Your discretion code optimization.).

Instructions for inserting into the table Details of the value of the selected variation

  1. В файле \wp-content\themes\{Ваша тема}\inc\woocommerce.php ищете
    <input type="hidden" name="variation_id" value="0" />
    и дописываете ему id="variation_id".
    Это необходимо для отслеживания изменения данного поля с id выбранной вариации.
  2. Идем в файл \wp-content\themes\{Ваша_тема}\woocommerce\single-product\add-to-cart\variation.php
    Инициализируем Все необходимые поля. И скрываем в публичной части сайта. {У меня есть свои кастомные поля, можете посмотреть, как их добавлять в админке, ищите по ключевым словам "woocommerce_wp_text_input" "load_variation_settings_fields" }
    variation.php

    <script type="text/template" id="tmpl-variation-template">
    <div class="woocommerce-variation-description" style="display:none;">
    {{{ data.variation.variation_description }}}
    </div>
    <div class="woocommerce-sleep_place-description" style="display:none;">
    {{{ data.variation.sleep_place }}}
    </div>
    <div class="woocommerce-volume-description" style="display:none;">
    {{{ data.variation.volume }}}
    </div>
    <div class="woocommerce-volume-description" style="display:none;">
    {{{ data.variation.cloth_type }}}
    </div>
    <div class="woocommerce-variation-availability" style="display:none;">
    {{{ data.variation.availability_html }}}
    </div>
    <div class="woocommerce-open_size-availability" style="display:none;">
    {{{ data.variation.open_size }}}
    </div>
    <div class="woocommerce-max_load-availability" style="display:none;">
    {{{ data.variation.max_load }}}
    </div>
    <div class="woocommerce-carcas_material-availability" style="display:none;">
    {{{ data.variation.carcas_material }}}
    </div>
    <div class="woocommerce-prod_time-availability" style="display:none;">
    {{{ data.variation.prod_time }}}
    </div>
    <div class="woocommerce-garantee-availability" style="display:none;">
    {{{ data.variation.garantee }}}
    </div>
    <div class="woocommerce-variation-price">
    {{{ data.variation.price_html }}}
    </div>
    </script>


  3. В functions.php Вашей активной темы прописываете JS, где производится сбор скрытых ранее полей атрибутов, очищение таблицы "Детали" и формирование новой
    Код в functions.php

    add_action( 'wp_footer', 'variations_change_javascript', 99999 ); // для фронта
    function variations_change_javascript() { ?>
    <script>
    function empty( mixed_var ) {	// Determine whether a variable is empty
      return ( mixed_var === "" || mixed_var === 0   || mixed_var === "0" || mixed_var === null  
          || mixed_var === false  ||  ( Array.isArray(mixed_var) && mixed_var.length === 0 ) );
    }
    
    jQuery(document).ready(function($) {
      
      var attributes = new Map(); 
      
      jQuery("#variation_id").bind("change", function() {
          // console.log("ID: " + jQuery(this).val()); 
         
         if($(".sku").text().length > 0) {
            attributes.set('Артикул',$(".sku").text()+"");
         }
         if ($(".woocommerce-sleep_place-description").text().length > 0) {
           attributes.set('Спальное место, мм',$(".woocommerce-sleep_place-description").text()+"");
         }
         if ($(".woocommerce-volume-description").text().length > 0) {
           attributes.set('Объем, кб. м',$(".woocommerce-volume-description").text()+"");
         }
         if ($(".woocommerce-open_size-availability").text().length > 0) {
           attributes.set('Габариты в разложенном виде, мм',$(".woocommerce-open_size-availability").text()+"");
         }
         if ($(".woocommerce-max_load-availability").text().length > 0) {
           attributes.set('Максимальная нагрузка, кг',$(".woocommerce-max_load-availability").text()+"");
         }
         if ($(".woocommerce-carcas_material-availability").text().length > 0) {
           attributes.set('Материалы каркаса',$(".woocommerce-carcas_material-availability").text()+"");
         }
         if ($(".woocommerce-prod_time-availability").text().length > 0) {
           attributes.set('Сроки изготовления',$(".woocommerce-prod_time-availability").text()+"");
         }
         if ($(".woocommerce-garantee-availability").text().length > 0) {
           attributes.set('Гарантия изготовителя',$(".woocommerce-garantee-availability").text()+"");
         }
        
        jQuery(".options-product tbody").empty();
        var fields="";
        
        if (attributes.size > 0) {
          
          attributes.forEach(function(value, key) {
            
            if(value.length > 0){
              fields+='<tr>';
              fields+='<th class="product-attributes-item__label">'+key+'</th>';
              fields+='<td class="product-attributes-item__value">'+value+'</td>';
              fields+='</tr>';
              jQuery(".options-product tbody").append(fields);
              fields = "";
            }
          });
        
        }
        
      }); 
      
      
     });
        </script>	
    <?}


  4. Получаете то, что нужно. Код можно доработать, чем я и занимаюсь
    60ec3409315c1274274278.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question