How to add custom user meta data in a WooCommerce sign up form
Posted on 2 March 2023
Step 1: Create the Custom User Meta Data Field
The first step is to create the custom user meta data field that you want to add to the WooCommerce sign-up form. You can add this code to your theme’s functions.php file or create a new plugin:
// Add custom user meta data field function add_custom_user_meta_data_field( $fields ) {
$fields['custom_field'] = array( 'label' => __( 'Custom Field', 'woocommerce' ), 'required' => true, 'class' => array( 'form-row-wide' ),
'clear' => true, 'priority' => 30, );
return $fields; }
add_filter( 'woocommerce_register_form_fields', 'add_custom_user_meta_data_field' );
In this example, we’re adding a custom field called “Custom Field” to the WooCommerce sign-up form. You can customize the label, class, and priority of the field to suit your needs.
Step 2: Save the Custom User Meta Data Field
The next step is to save the custom user meta data field when the user submits the sign-up form. You can add this code to your theme’s functions.php file or create a new plugin:
// Save custom user meta data field function save_custom_user_meta_data_field( $customer_id )
{ if ( isset( $_POST['custom_field'] ) ) {
update_user_meta( $customer_id, 'custom_field', sanitize_text_field( $_POST['custom_field'] ) );
} }
add_action( 'woocommerce_created_customer', 'save_custom_user_meta_data_field' );
In this example, we’re saving the custom field called “Custom Field” to the user’s meta data using the update_user_meta function. You can customize the meta key to suit your needs.
Step 3: Display the Custom User Meta Data Field
Finally, you may want to display the custom user meta data field on the WooCommerce My Account page or on the WooCommerce order details page. You can add this code to your theme’s functions.php file or create a new plugin:
// Display custom user meta data field
function display_custom_user_meta_data_field() {
$custom_field = get_user_meta( get_current_user_id(), 'custom_field', true );
if ( $custom_field ) {
echo '<p><strong>' . __( 'Custom Field', 'woocommerce' ) . ':</strong> ' . $custom_field . '</p>';
} }
add_action( 'woocommerce_account_dashboard', 'display_custom_user_meta_data_field' );
add_action( 'woocommerce_view_order', 'display_custom_user_meta_data_field' );
In this example, we’re displaying the custom field called “Custom Field” on the WooCommerce My Account page and on the WooCommerce order details page using the get_user_meta function. You can customize the display of the field to suit your needs.
Conclusion
By following these three steps, you can add custom user meta data to a WooCommerce sign-up form. This can be useful for collecting additional information from customers during the sign-up process or for storing custom information about customers for future use.