Phone Number Field on Registration and Profiles
Adds a phone number field to the WordPress registration form, saves it with the new account and lets users and admins edit it on the profile screen.
Opens WPIDE on
Code
$wpide_phone_required = true;
add_action( 'register_form', function () use ( $wpide_phone_required ) {
$value = isset( $_POST['wpide_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['wpide_phone'] ) ) : '';
printf( '<p><label for="wpide_phone">Phone number</label><input type="tel" name="wpide_phone" id="wpide_phone" class="input" value="%s" autocomplete="tel"%s></p>', esc_attr( $value ), $wpide_phone_required ? ' required' : '' );
} );
add_filter( 'registration_errors', function ( $errors ) use ( $wpide_phone_required ) {
$phone = isset( $_POST['wpide_phone'] ) ? (string) wp_unslash( $_POST['wpide_phone'] ) : '';
$digits = strlen( preg_replace( '/\D/', '', $phone ) );
if ( ( $wpide_phone_required || '' !== $phone ) && ( $digits < 7 || $digits > 15 || ! preg_match( '/^\+?[0-9\s().\-]+$/', $phone ) ) ) {
$errors->add( 'wpide_phone', '<strong>Error:</strong> Please enter a valid phone number.' );
}
return $errors;
} );
add_action( 'user_register', function ( $user_id ) {
if ( isset( $_POST['wpide_phone'] ) ) {
update_user_meta( $user_id, 'phone', sanitize_text_field( wp_unslash( $_POST['wpide_phone'] ) ) );
}
} );
add_filter( 'user_contactmethods', function ( $methods ) {
$methods['phone'] = 'Phone number';
return $methods;
} );
Notes
Set $wpide_phone_required to false to make it optional; the number is stored in user meta named phone.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.