Published:
Want to add an extra layer of security to your WordPress login page? In this tutorial, you’ll learn how to insert a custom field into the login form and validate it using WordPress hooks — all without touching core files.
First of all, I would advise against editing the core files as it will be overwritten when you next update WordPress.
Also, you should update WordPress, because it will often include security updates. (It's recently been reported that there has been a spate of attacks on sites using outdated WordPress versions)
In order to achieve what you actually want to do, I recommend you use hooks as the best way to edit WordPress.
As such, to create an extra field on your login page, you may use the login_form action hook:
In theme's functions.php:
// Add custom field to login form using the 'login_form' hook
add_action('login_form','my_added_login_field');
function my_added_login_field(){
//Your HTML
?>
<p>
<label for="my_extra_field">My extra field<br>
<input type="text" tabindex="20" size="20" value="" class="input" id="my_extra_field" name="my_extra_field_name"></label>
</p>
<?php
}
Next we need to verify that what they entered into the field matched what you have stored. In the following code, I've assumed you've stored the identification code as a user meta value with meta key my_ident_code. You should do this rather than create your own column!. See the Codex pages for
add_user_meta function
update_user_meta function
get_user_meta function
To verify a user you can use the authenticate filter. This passes the entered username and password. If the identification code is correct, return null to allow WordPress to verify the password and username. If it is not correct, remove the WordPress' authentication and return an error. This forces the user back to the log-in page, where they'll see the error displayed.
Also add following code to your theme's functions.php :
// Authenticate user and validate custom field using the 'authenticate' filter
add_filter( 'authenticate', 'my_custom_authenticate', 10, 3 );
function my_custom_authenticate( $user, $username, $password ){
//Get POSTED value
$my_value = sanitize_text_field($_POST['my_extra_field_name']);
//Get user object
$user = get_user_by('login', $username );
//Get stored value
$stored_value = get_user_meta($user->ID, 'my_ident_code', true);
if(!$user || empty($my_value) || $my_value !=$stored_value){
//User not found, or no value entered- don't proceed.
remove_action('authenticate', 'wp_authenticate_username_password', 20);
remove_action('authenticate', 'wp_authenticate_email_password', 20);
//Create an error to return to user
return new WP_Error( 'denied', __("<strong>ERROR</strong>: Your additional authentication code is incorrect.") );
}
//Make sure you return null
return null;
}
Always test new login-related features in a staging environment before applying them to a live site. This prevents lockouts and ensures smooth user experience.