In order to add a custom field to the user registration form in WooCommerce, you need to follow a few simple steps.
First, log in to your WordPress dashboard and navigate to WooCommerce > Settings. On the Settings page, click on the Accounts tab. In the Registration Form section, you will have the option to add new fields to the form. Simply enter the desired field label and choose whether it is required or not. Once you have added the field, click the Save Changes button.
Next, you will need to add some code in order to save the data entered in the custom field. You can do this by adding the following code to your theme’s functions.php file or in a custom plugin:
function save_extra_register_fields( $user_id ) {
if ( isset( $_POST['extra_field'] ) ) {
update_user_meta( $user_id, 'extra_field', sanitize_text_field( $_POST['extra_field'] ) );
}
}
add_action( 'user_register', 'save_extra_register_fields' );
Once the custom field data is saved, it will be stored as user meta data. To display this data on the user’s profile page, add the following code:
function extra_profile_fields( $user ) { ?>
<h3>Extra Profile Information</h3>
<table class="form-table">
<tr>
<th><label for="extra_field">Extra Field</label></th>
<td>
<input type="text" name="extra_field" id="extra_field" value="<?php echo esc_attr( get_the_author_meta( 'extra_field', $user->ID ) ); ?>" class="regular-text" /><br />
<span class="description">Please enter your extra field information here.</span>
</td>
</tr>
</table>
<?php }
if ( current_user_can( 'edit_users' ) ) {
add_action( 'show_extra_user_profile_fields', 'extra_profile_fields' );
}
Make sure that the action hook is added only if the current user can edit user profiles (i.e., is an administrator).
By following these steps, you can easily add a custom field to the user registration form in WooCommerce, save the data entered in the field, and display it on the user’s profile page.