How to Add WooCommerce Custom Text Field for all Variations

0
287

I need it to add a custom text field for every variations in WooCommerce products. I figure out a code that helped me do that.

// Add Variation Custom fields

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

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

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

    echo '<div class="variation-custom-fields">';

    // Text Field
    woocommerce_wp_text_input(
        array(
            'id'          => '_wood_price['. $loop .']',
            'label'       => __( 'Price variation for wood type', 'woocommerce' ),
            'placeholder' => '',
            //'desc_tip'    => true,
            'wrapper_class' => 'form-row form-row-first',
            //'description' => __( 'Enter the custom value here.', 'woocommerce' ),
            'value'       => get_post_meta($variation->ID, '_wood_price', true)
        )
    );
    echo "</div>";

}

/** Save new fields for variations */
function save_newvariation_fields( $variation_id, $i) {

    // Text Field
    $text_field = stripslashes( $_POST['_wood_price'][$i] );
    update_post_meta( $variation_id, '_wood_price', esc_attr( $text_field ) );

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here