'Wordpress login with username, email and custom meta field
I'm working on a custom Wordpress login form. At the moment users are able to login with their username or email but i also want to add the option to user their account-number. The account number is a custom metafield and is different form the id.
I've found the following hooks
- wp_authenticate_user
- wp_authenticate_username_password
but i've online seen options to remove the username of email not ways to add meta fields.
Kind regards
Solution 1:[1]
You need to add account number field to login form and then check or validate according to your need using wp_authenticate_user hook.
So you can try something like this:
//Add account number field on login form
add_action( 'login_form', 'myplugin_add_login_fields' );
function myplugin_add_login_fields() {
$account_number = ( isset( $_POST['account_number'] ) ) ? $_POST['account_number'] : '';
?>
<p>
<label for="account_number"><?php _e('Account Number','mydomain') ?><br />
<input type="text" name="account_number" id="account_number" class="input" value="<?php echo esc_attr(stripslashes($account_number)); ?>" size="25" /></label>
</p>
<?php
}
//check if account number is present or throw error if its not provided by the user.
//do any extra validation stuff here e.g. get account number from DB
add_filter('wp_authenticate_user','check_account_number', 10, 2);
function check_account_number($user, $password) {
$return_value = $user;
$account_number = ( isset( $_POST['account_number'] ) ) ? $_POST['account_number'] : '';
if(empty($account_number)) {
$return_value = new WP_Error( 'empty_account_number', 'Please enter account number.' );
}
//stop user from logging in if its account number is incorrect
$account_number_db = get_user_meta($user->ID, 'lidnummer', true);
if($account_number_db != $account_number) {
$return_value = new WP_Error( 'invalid_account', 'Please enter your correct account number.' );
}
return $return_value;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
