User Registration

Step by step documentation to set up a user registration form for your website.

Custom Code Snippets

Table of Contents

Here, you will find some custom code snippets for various functions that you won’t get on the available plugin settings. This list will keep on updating as we move forward.

Wanna know how to add these custom code snippet?

User Roles #

Give multiple user roles #

As the name suggests, this code will give two roles to the users. It will make the user an admin and an editor. You can add or remove roles from the code as per your need.

add_filter( 'user_registration_after_register_user_action', 'ur_add_user_role', 10, 3 );
function ur_add_user_role( $form_data, $form_id, $user_id ) {
	if ( in_array( $form_id, array( 40 ), true ) ) {
			$user     = new WP_User( $user_id );
			$new_role = array( 'administrator', 'editor' ); // New role to assign to user.
			foreach ( $new_role as $role ) {
			$user->add_role( $role );
		}
	}
}

Username Validations #

For username to be the entered email #

This code will set the email address you have entered as the username for the respective user.

add_filter( 'user_registration_before_insert_user', 'ur_insert_username', 10, 3 );
function ur_insert_username( $user_data, $valid_form_data, $form_id ) {
    $user_data['user_login'] = $valid_form_data['user_email']->value;
    return $user_data;
}

add_filter( 'user_registration_before_register_user_filter', 'ur_set_email_as_username', 10, 2 );
function ur_set_email_as_username( $valid_form_data, $form_id ) {
    $valid_form_data['user_login'] = $valid_form_data['user_email'];
    return $valid_form_data;
}

Show First Name and Last Name as the username #

This code will concat the first and last name and use it as the username.

add_action( 'user_registration_after_register_user_action', 'ur_insert_username', 1, 3 );
function ur_insert_username( $valid_form_data, $form_id, $user_id ) {
    global $wpdb;
    $firstname = isset( $valid_form_data['first_name'] ) ? $valid_form_data['first_name']->value : '';
    $lastname = isset( $valid_form_data['last_name'] ) ? $valid_form_data['last_name']->value : '';
    $custom_username =  $firstname . "-" . $lastname;
    $user = get_user_by('login', $custom_username);
   
    if( ! empty( $user ) ) {
        $custom_username =  $custom_username ."-" . $user_id;
    }
    $wpdb->update(
        $wpdb->users,
        ['user_login' => $custom_username],
        ['ID' => $user_id]
    );
}

Validation Messages #

Customize the ‘Email already exists’ message #

The code will change the ‘Email already exists’ message to the custom message you put. Just replace ‘Your message goes here’ with your custom message.

add_filter( 'user_registration_validate_user_email_message', 'user_registration_user_email_error_message', 11, 1 );
function user_registration_user_email_error_message( $msg ) {
	if ( 'Email already exists.' === $msg ) {
		return __( 'Your Error Message goes here.', 'user-registration' );
	} else {
		return $msg;
	}
}
Email Suggestion #

If you see ‘Did you mean @example.com?’ when you add an email, use the following code. This removes the Email Suggestion.

add_filter( 'user_registration_mailcheck_enabled', 'false' );
function false() {
return false;
}

Change the error message during lost password #

This code will replace the error message that says ‘Invalid username or email’ with your custom message.

add_filter( 'user_registration_add_error',function( $message ){
 if( 'Invalid username or email.' ===  $message ) {
    $message = __('your custom message','user-registration');
 }
return $message;
});

Change Lost Password Description #

add_filter( 'user_registration_lost_password_message', function( $msg ){
           $msg = __( "Enter text","user_registration");
           return $msg;
});

Redirection Specifics #

Redirect to a different page after clicking on the Email Confirmation URL #

Replace the URL with your desired URL on the code below.

add_action( 'user_registration_check_token_complete', 'ur_auto_login_email_verification', 10, 2 );
    function ur_auto_login_email_verification( $user_id, $user_reg_successful ) {
        if( true === $user_reg_successful ) {
            wp_set_auth_cookie( $user_id );
            $form_id_array = get_user_meta( $user_id, 'ur_form_id' );
            $form_id       = 0;
        $url = '';
            if ( isset( $form_id_array[0] ) ) {
                $form_id = $form_id_array[0];
            }
        if ( '4178' === $form_id ) {
            $url = "https://userregistration.dev/member/";
            } else if ( '4208' === $form_id ) {
            $url = "https://userregistration.dev/partner/";
            }
            wp_safe_redirect( $url );
            die();
        }
    }

Redirect to Homepage after Social Login #

Use the following code to redirect the users to the Homepage once they login using social sites.

add_filter( 'user_registration_social_connect_login_redirect', 'user_registration_redirect_after_social_login' );
function user_registration_redirect_after_social_login( $redirect_url ) {
	$redirect_url = home_url();
	return $redirect_url;
}

Redirect back to the previous page after registration #

add_filter('user_registration_form_redirect_url', 'ur_redirect_back_original_referer', 10, 2);

function ur_redirect_back_original_referer($redirect_url, $form_id) {

    if (isset($_SERVER['HTTP_REFERER'])) {
        $redirect_previous_url = $_SERVER['HTTP_REFERER'];
        return $redirect_previous_url;
    }

    return $redirect_url;
}

No redirection on auto-login. #

If you select no redirection on the registration form but select auto-login in the user login options, the users will be redirected to the My Account page once they register. To stop this, use the following code.

add_filter( 'user_registration_auto_login_redirection', function( $redirect_url ){
    $redirect_url = '';
    return $redirect_url;
});

WooCommerce Specifics #

Populate the first name and last name with the input given on the billing first name and last name #

add_action( 'user_registration_after_register_user_action', 'ur_update_first_last_name', 10, 3 );
    function ur_update_first_last_name( $valid_form_data, $form_id, $user_id ) {
        $first_name = '';
        $last_name = '';
        if ( isset( $valid_form_data['billing_first_name'] ) && ! empty( $valid_form_data['billing_first_name']->value ) ) {
            $first_name = $valid_form_data['billing_first_name']->value;
        }
        if ( isset( $valid_form_data['billing_last_name'] ) && ! empty( $valid_form_data['billing_last_name']->value ) ) {
            $last_name = $valid_form_data['billing_last_name']->value;
        }
        if ( ! empty( $first_name ) || ! empty( $last_name ) ) {
            $user_data = array(
            'ID' => $user_id, // this is the ID of the user you want to update.
            'first_name' => $first_name,
            'last_name' => $last_name,
            );
wp_update_user( $user_data );
} 
}

Populate the billing first name and last name with the input given on the first name and last name #

add_action( 'user_registration_after_register_user_action', 'ur_update_first_last_name', 10, 3 );
        function ur_update_first_last_name( $valid_form_data, $form_id, $user_id ) {
            $first_name = '';
            $last_name = '';
            if ( isset( $valid_form_data['first_name'] ) && ! empty( $valid_form_data['first_name']->value ) ) {
                $first_name = $valid_form_data['first_name']->value;
            }
            if ( isset( $valid_form_data['last_name'] ) && ! empty( $valid_form_data['last_name']->value ) ) {
                $last_name = $valid_form_data['last_name']->value;
            }
            if ( ! empty( $first_name ) ) {
                update_user_meta( $user_id, 'billing_first_name', $first_name );
            }
            if ( ! empty( $last_name ) ) {
                update_user_meta( $user_id, 'billing_last_name', $last_name );
            }
}

Show custom form field data on the Order Details email. #

add_action( 'woocommerce_email_order_details', 'add_to_order_email', 10, 4);

 

function add_to_order_email( $order, $sent_to_admin, $plain_text, $email ) {
    $customer_id = $order->data['customer_id'];
    $field_value = get_usermeta( $customer_id, "user_registration_check_box_1681727778" );

    $field_value = is_array( $field_value ) ? implode( ',', $field_value ) : $field_value;

 

        echo "This is extra details.";
        echo "Field Label = " . $field_value;
}
Please make sure you have synced the User Registration form with the WooCommerce checkout form. Check this link to know more about this.

Fields Specifics #

Limit Username character length #

The code below will limit the character length of the username field to a maximum of 15 characters only.

add_action( 'user_registration_validate_user_login', 'ur_validate_user_login_field', 10, 4 );
function ur_validate_user_login_field( $single_form_field, $data, $filter_hook, $form_id ) {
	$field_label = isset( $data->label ) ? $data->label : '';
	$username       = isset( $data->value ) ? $data->value : '';
	if ( 15 < strlen( $username ) ) {
		add_filter(
		$filter_hook,
		function ( $msg ) use ( $field_label ) {
		return __( $field_label . ' cannot exceed 15 characters.', 'user-registration' );
		}
		);
	}
}

Limit Number length #

add_action( 'user_registration_validate_number','ur_validate_number_field',10,4);
function ur_validate_number_field($single_form_field, $data, $filter_hook, $form_id) {    
    $field_label = isset( $data->label ) ? $data->label : '';
    $value = isset( $data->value ) ? $data->value : '';
    if( 'number_box_1690949145' === $single_form_field->general_setting->field_name ) {
        if(!preg_match('/^\d{5}$/', $value ) ) {
            add_filter( $filter_hook, function ( $msg ) use ( $field_label ) {
                return __( $field_label . ' Need to be Exactly 5 Digits.', 'user-registration' );
           });
        }
    }
}

Remove space ‘ ‘ in the username #

This code snippet will help you remove the space/whitespace, if any, between the value entered in the username field.

add_filter( 'validate_username', 'custom_validate_username', 10, 2 );
function custom_validate_username( $valid, $username ) {
		if ( preg_match( '/\\s/', $username ) ) {
		there are spaces
		return $valid = false;
		}
	return $valid;
}

Display only the specific countries on the Country Dropdown #

This code will show ‘Sweden’ and the ‘Denmark’ as the only available options on the country dropdown.

add_filter( 'user_registration_countries_list', 'display_specific_only' );
function display_specific_only( $country_list ) {
		$country_list = array( '' => '--Select--', 'SE' => __( 'Sweden', 'user-registration' ), 'DK' => __( 'Denmark', 'user-registration' ) );
		return $country_list;
		}
For WooCommerce Billing Country Field #
add_filter( 'user_registration_billing_country_frontend_form_data', 'display_specific_country', 11 );
function display_specific_country( $data ) {
    $data['form_data']['options'] = array( '' => '--Select--', 'AU' => __( 'Australia', 'user-registration' )
	 );
    return $data;
}

Add a new file type in the File Upload field #

If you want to add a custom file type that is not available in the default settings of the File Upload field, you can use the following code. This will add file types CSV and xls.

add_filter( 'user_registration_file_upload_valid_file_type', 'urfu_add_new_valid_file_type', 10, 1 );
function urfu_add_new_valid_file_type( $validTypes ) {
$newTypes = array(
'text/csv' => __( 'CSV test', 'user-registration-file-upload' ),
'application/vnd.ms-excel' => __( 'XLS test', 'user-registration-file-upload' ),
);
$validTypes = array_merge( $validTypes, $newTypes );
return $validTypes;
}

Please visit this URL to check the MIME file type for various files.

Misc #

Change Email Content of Password Changed Email #

Password changed email content is hard coded into the plugin files and editing content can be done with the following codes at this moment.

// Define a function to modify the password change email content
function custom_password_change_email( $pass_change_mail, $user ) {
    // Customize the email content here
    $pass_change_mail['subject'] = 'Your Password has been changed'; // Change email subject
    $pass_change_mail['message'] = "Hi " . $user->display_name . ",\n\n";
    $pass_change_mail['message'] .= "Your password has been changed successfully.\n\n";
    $pass_change_mail['message'] .= "If you did not change your password, please contact us immediately.\n\n";
    $pass_change_mail['message'] .= "Regards,\n";
    $pass_change_mail['message'] .= "Your Website Name";
    
    return $pass_change_mail;
}
add_filter( 'password_change_email', 'custom_password_change_email', 10, 2 );

Show ‘Log In’ when logged out and ‘My Account’ when logged in on the Primary Menu #

As the name suggests, this code will show Log In when logged out and ‘My Account’ when logged in on the primary menu of your site.

function ur_login_menu_hide( $items ) {
   $login_url = 'http://wpeverest.test/test-user-registration-login/'; // Your login page url.
   if ( is_user_logged_in() ) {
       if ( is_array( $items ) ) {
           foreach ( $items as $key => $item ) {
               if ( $login_url === $item->url ) {
                   $items[ $key ]->title = 'Profile';
               }
           }
       }
   }
   return $items;
}
add_filter( 'wp_nav_menu_objects', 'ur_login_menu_hide', 10 );
Show ‘username’ instead of ‘My Account’ #
function ur_login_menu_hide( $items ) {
   $login_url = 'http://wpeverest.test/test-user-registration-login/'; // Your login page url.
   if ( is_user_logged_in() ) {
       $current_user = wp_get_current_user();
       $username = $current_user->user_login;
       if ( is_array( $items ) ) {
           foreach ( $items as $key => $item ) {
               if ( $login_url === $item->url ) {
                   $items[ $key ]->title = $username;
               }
           }
       }
   }
   return $items;
}
add_filter( 'wp_nav_menu_objects', 'ur_login_menu_hide', 10 );

Remove the user_registration prefix from custom fields #

add_action( 'user_registration_after_register_user_action', 'create_user_type_meta', 10, 3 );

function create_user_type_meta( $form_data, $form_id, $user_id ) {

 foreach($form_data as $key => $value){
	$user_type = isset( $form_data[$key] ) ? $form_data[$key]->value : '';
	update_user_meta( $user_id, $key, $user_type );
 }
}

Send data to an external URL with WebHook when the profile details are changed. #


add_action('user_registration_save_profile_details', 'ur_post_submission_after_profile_update', 10, 2);
function ur_post_submission_after_profile_update($user_id, $form_id)
{
    $profile = user_registration_form_data($user_id, $form_id);
    $valid_form_data   = ur_get_valid_form_data($profile);
    $fields_to_exclude = ur_exclude_fields_in_post_submssion();

    foreach ($fields_to_exclude as $key => $value) {
        if (isset($valid_form_data[$value])) {
            unset($valid_form_data[$value]);
        }
    }

    if (null !== get_option('user_registration_pro_general_post_submission_settings')) {
        $url          = get_option('user_registration_pro_general_post_submission_settings');
        $single_field = array();

        foreach ($valid_form_data as $data) {
            $single_field[$data->field_name] = isset($data->value) ? $data->value : '';
        }

        if ('post_json' === get_option('user_registration_pro_general_setting_post_submission', array())) {
            $headers = array('Content-Type' => 'application/json; charset=utf-8');
            wp_remote_post(
                $url,
                array(
                    'body'    => json_encode($single_field),
                    'headers' => $headers,
                )
            );
        } elseif ('get' === get_option('user_registration_pro_general_setting_post_submission', array())) {
            $url = $url . '?' . http_build_query($single_field);
            wp_remote_get($url);
        } else {
            wp_remote_post($url, array('body' => $single_field));
        }
    }
}

function ur_get_profile_update_post_data()
{
    $single_field = array();

    // Handle if edit profile saving as ajax form submission.
    if (ur_string_to_bool(get_option('user_registration_ajax_form_submission_on_edit_profile', false))) {
        $form_data = isset($_POST['form_data']) ? json_decode(stripslashes($_POST['form_data'])) : array();
        foreach ($form_data as $data) {
            $single_field[$data->field_name] = isset($data->value) ? $data->value : '';
        }
    } else {
        $single_field = $_POST;
    }
    return $single_field;
}

function ur_get_valid_form_data($profile)
{
    $single_field = ur_get_profile_update_post_data();
    $valid_form_data = array();
    
    foreach ($single_field as $post_key => $post_data) {
        $pos = strpos($post_key, 'user_registration_');

        if (false !== $pos) {
            $new_string = substr_replace($post_key, '', $pos, strlen('user_registration_'));
        } else {
            $new_string = $post_key;
        }
        if (!empty($new_string)) {
            $tmp_array       = ur_get_valid_form_data_format($new_string, $post_key, $profile, $post_data);
            $valid_form_data = array_merge($valid_form_data, $tmp_array);
        }
    }

    return $valid_form_data;
}
You will need the User Registration Pro to achieve this. The Post Submission feature must be used along with the above code.

Customize the ‘Passwordless login’ email content #

function modify_passwordless_login_message($message, $email, $magic_link_url) {

    $message = sprintf(
        __(
            'Hello %1$s,<br><br>You have requested to log in to your account without a password.<br>Click the following link to log in: <a href="%2$s">%3$s</a><br><br>If you did not request this login, please ignore this email.<br><br>Customized Message Text Goes Here<br><br>Thank you,<br>%4$s',
            'user-registration-pro'
        ),
        esc_html($email),
        esc_url($magic_link_url),
        esc_html($magic_link_url),
        esc_html(get_bloginfo('name'))
    );

    return $message;
}

add_filter('ur_magic_login_link_email_message', 'modify_passwordless_login_message', 10, 3);

Extend the WP login session. #

function extend_user_session() {
    if (is_user_logged_in()) {
        $session_expiration = 3 * 30 * 24 * 60 * 60; // 3 months in seconds
        setcookie('wordpress_logged_in', $_COOKIE['wordpress_logged_in'], time() + $session_expiration, '/');
        setcookie('wordpress_sec', $_COOKIE['wordpress_sec'], time() + $session_expiration, '/');
    }
}
add_action('init', 'extend_user_session');

Auto Login after Email Confirmation #

add_action(
    'user_registration_check_token_complete',
    'ur_auto_login_after_email_confirmation',
    10,
    2
);

function ur_auto_login_after_email_confirmation($user_id, $user_reg_successful) {
    global $wp;

    if (!$user_id) {
        return;
    }

    if (ur_string_to_bool($user_reg_successful)) {
        wp_clear_auth_cookie();
        wp_set_auth_cookie($user_id);
        wp_safe_redirect(home_url(add_query_arg(array(), $wp->request)));
    }
}

Add currency for missing countries #

This will show an example of the Georgian currency.

add_filter( 'user_registration_payments_currencies', 'ur_support_gel_currencies' );
function ur_support_gel_currencies( $currencies ) {
$extra_currencies = array(
'GEL' => array(
'name' => esc_html__( 'Georgian Lari', 'user-registration' ),
'symbol' => '&#x20BE;', // Georgian Lari symbol
'symbol_pos' => 'left',
'thousands_separator' => ',',
'decimal_separator' => '.',
'decimals' => 2,
),
);

$currencies = array_merge( $currencies, $extra_currencies );
return $currencies;
}

Customize the ‘You are currently logged in’ message. #

add_filter( 'user_registration_logged_in_message', 'user_registration_logged_in_message_change', 10, 1 );
function user_registration_logged_in_message_change( $message ) {
return sprintf( ( 'You are already logged in. Please click on <a href="%s">log out</a> and refresh this page again.', 'user-registration' ), ur_logout_url() );
}

Powered by BetterDocs

Scroll to top