Skip to content

Instantly share code, notes, and snippets.

@mcnaveen
Created October 18, 2020 19:46
Show Gist options
  • Save mcnaveen/917fc756f163596ca80e1b7e14233f9f to your computer and use it in GitHub Desktop.
Save mcnaveen/917fc756f163596ca80e1b7e14233f9f to your computer and use it in GitHub Desktop.
Add Custom Fields to WooCommerce Checkout and Store in Order Details Page
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
echo '<div id="my_custom_checkout_field"><h3>'.__('My Field').'</h3>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'text',
'class' => array('my-field-class orm-row-wide'),
'label' => __('Fill in this field'),
'required' => true,
'placeholder' => __('Enter a number'),
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
/**
* Process the checkout
**/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
global $woocommerce;
if ( ! $_POST['my_field_name'] )
wc_add_notice( __( 'Please fill My Field.' ), 'error' );
}
/**
* Update the user meta with field value
**/
add_action('woocommerce_checkout_update_user_meta', 'my_custom_checkout_field_update_user_meta');
function my_custom_checkout_field_update_user_meta( $user_id ) {
if ($user_id && $_POST['my_field_name']) update_user_meta( $user_id, 'my_field_name', esc_attr($_POST['my_field_name']) );
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['my_field_name']) update_post_meta( $order_id, 'My Field', esc_attr($_POST['my_field_name']));
}
/**
* Add the field to order emails
add_filter('woocommerce_email_order_meta_keys', 'my_custom_checkout_field_order_meta_keys');
function my_custom_checkout_field_order_meta_keys( $keys ) {
$keys[] = 'My Field';
return $keys;
} **/
@anuranjanverma
Copy link

It is working. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment