Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.