O
O
Oaks2015-10-23 18:04:17
PHP
Oaks, 2015-10-23 18:04:17

How to add a custom field to a variable product in Woocommerce?

Hello!
How to add an arbitrary field to a variable product and display it in content-product.php
Using ACF, I do this:
I create a rule record type -> equals -> product_variation
Text field
And for some reason it is not visible in the variation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WP Panda, 2015-10-24
@oaksaudio

Why are you all clinging to these plugins for fields?
Using ACF and its analogs is bad practice, it's very bad practice, it's very very bad practice.
Both WordPress and WooCommerce have a corresponding API
. For a variable product, a little simple code.

add_action( 'woocommerce_product_after_variable_attributes', 'cr_variable_fields', 10, 3 );
add_action( 'woocommerce_product_after_variable_attributes_js', 'cr_variable_fields_js' );
add_action( 'woocommerce_process_product_meta_variable', 'save_cr_variable_fields', 10, 1 );

/**
 * Создает новое поле
*/
function cr_variable_fields( $loop, $variation_data, $variation ) {
?>
  <tr>
    <td>
      <?php
      woocommerce_wp_text_input( 
        array( 
          'id'          => '_text_field['.$loop.']', 
          'label'       => __( 'Мое текстовое поле', 'woocommerce' ), 
          'placeholder' => __( 'Подсказка', 'woocommerce' ), 
          'desc_tip'    => 'true',
          'description' => __( 'Введите ваше значение.', 'woocommerce' ),
          'value'       => get_post_meta( $variation->ID, '_text_field', true )
        )
      );
      ?>
    </td>
  </tr>
  
<?php
}

/**
 * Создает поле нового варианта
*/
function cr_variable_fields_js() {
?>
  <tr>
    <td>
      <?php
      woocommerce_wp_text_input( 
        array( 
          'id'          => '_text_field[ + loop + ]', 
          'label'       => __( 'Мое текстовое поле', 'woocommerce' ),  
          'placeholder' => __( 'Подсказка', 'woocommerce' ),
          'desc_tip'    => 'true',
          'description' => __( 'Введите ваше значение.', 'woocommerce' ),
          'value'       => ''
        )
      );
      ?>
    </td>
  </tr>
<?php
}

/**
 * Сохраняет поле
*/
function save_cr_variable_fields( $post_id ) {
  if (isset( $_POST['variable_sku'] ) ) :
    $variable_sku          = $_POST['variable_sku'];
    $variable_post_id      = $_POST['variable_post_id'];
    
    $_text_field = $_POST['_text_field'];
    for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
      $variation_id = (int) $variable_post_id[$i];
      if ( isset( $_text_field[$i] ) ) {
        update_post_meta( $variation_id, '_text_field', stripslashes( $_text_field[$i] ) );
      }
    endfor;

  endif;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question