The best way to extend WordPress and WooCommerce is by using hooks. To add custom option field on products area, you can use the following hooks:
- woocommerce_product_options_advanced: used to add a custom field into the Advanced Tab
- woocommerce_process_product_meta: used to save/update field data in the database
On your functions.php, you can add the following code:
/* create a new product field*/
add_action( 'woocommerce_product_options_advanced', 'personalization_product_options_adv' );
function personalization_product_options_adv() {
echo '<div class="options_group">';
woocommerce_wp_textarea_input( array(
'id' => 'product_personalization_note',
'value' => get_post_meta( get_the_ID(), 'product_personalization_note', true ),
'label' => 'Personalization Note',
'desc_tip' => true,
'description' => 'Allow product personalization for select products',
) );
echo '</div>';
}
/* save & update the changes*/
add_action( "woocommerce_process_product_meta", "personalization_save_fields" );
function personalization_save_fields( $post_id ) {
// grab the custom data from $_POST
$product_personalization_note = isset( $_POST[ 'product_personalization_note' ] ) ? sanitize_text_field( $_POST[ 'product_personalization_note' ] ) : '';
// grab the product
$product = wc_get_product( $post_id );
// save the custom data using WooCommerce built-in functions
$product->update_meta_data( 'product_personalization_note', $product_personalization_note );
//save
$product->save();
}
/* display the new field on single product pages */
function woocommerce_custom_fields_display() {
global $post;
$product = wc_get_product($post->ID);
$custom_fields_woocommerce_title = $product->get_meta('product_personalization_note');
if ($custom_fields_woocommerce_title) {
printf(
'<div><label>%s</label><input type="text" id="woocommerce_product_custom_fields_title" name="woocommerce_product_custom_fields_title" value=""></div>',
esc_html($custom_fields_woocommerce_title)
);
}
}
add_action('woocommerce_before_add_to_cart_button', 'woocommerce_custom_fields_display');
To retrieve this data in the frontend or emails sent by WooCommerce, you can use the regular get_post_meta() function like so:
$product_additional_note = get_post_meta( get_the_ID(), 'product_additional_note ', true );
Source: