danyaneh
11/10/2017 - 3:31 AM

WordPress WooCommerce Additional Fields

// Add Variation Custom fields

//Display Fields in admin on product edit screen
add_action( 'woocommerce_product_after_variable_attributes', 'woo_variable_fields', 10, 3 );

//Save variation fields values
add_action( 'woocommerce_save_product_variation', 'save_variation_fields', 10, 2 );

// Create new fields for variations
function woo_variable_fields( $loop, $variation_data, $variation ) {

  echo '<div class="variation-custom-fields">';
    
      // Text Field
      woocommerce_wp_text_input( 
        array( 
          'id'          => '_product_name_prepend['. $loop .']', 
          'label'       => __( 'Product variation name Prepend', 'woocommerce' ), 
          'placeholder' => 'A1.',
          'wrapper_class' => 'form-row form-row-first',
          'description' => __( 'This will show before the products name', 'woocommerce' ),
          'value'       => get_post_meta($variation->ID, '_product_name_prepend', true)
        )
      );

  echo "</div>"; 

}

/** Save new fields for variations */
function save_variation_fields( $variation_id, $i) {
    
    // Product Name prepend
    $product_name_prepend = stripslashes( $_POST['_product_name_prepend'][$i] );
    update_post_meta( $variation_id, '_product_name_prepend', esc_attr( $product_name_prepend ) );
}