WordPress Custom Forgot Password Page
X

Congrats, You are Subscribed to Receive Updates.

WordPress Custom Forget Password Page


WordPress Custom Forgot Password Page.  In my previous Article I explained how to create custom login page. With that custom page we will add Forgot password functionality.  If you have not checked it, Read Here. Alright, we need to use the same page for forgot password as well, we are going to use jQuery functions to switch the forms visibility to use it. Here is the jquery function and also we are going to give id to play with both forms.

<script src="<?php echo get_template_directory_uri();?>/assets/js/jquery-1.10.2.js"></script>
	<script> 
	$(document).ready(function(){
		$('#forgot_password').hide();
		
		$('#forgot-password').on('click', function(e) {
			e.preventDefault();			
			$('#forgot_password').show();
			$('#login-form').hide();
		});
		$('#have_id').on('click', function(e) {
			e.preventDefault();			
			$('#forgot_password').hide();
			$('#login-form').show();
		});
	
	});	
	</script>

Here, the “#forgot_password ” is the forgot password form , initialy we set it to hidden, once the user click the “#forgot-password”  link, it will be visible and the login form will be hidden. Let’s work on the form `#forgot_password`. We are writing two forms in one page. login form and forget password. So we need additional parameter to handle forms independently. So, the forget password will be having a textbox to get username or email from user, a submit button and a hidden field to differentiate the form. Also we will provide a link to goback to login form, if they clicked it by mistake. Now, Let’s see the form.

<form role="form" action="<?php echo "http://".$_SERVER["SERVER_NAME"].$_SERVER['REQUEST_URI']; ?>" method="post" >
 	<div class="form-group input-group">
 		<span class="input-group-addon">E-Mail or Username </span>
 		<input type="text" name="emailToreceive" class="form-control" placeholder="Your Username " required />
 	</div>
 
 	<div class="form-group"> 
 		<span class="pull-right">
			 <a href id="have_id" > Back to Login? </a> 
 		</span>
	 </div>
	 <input type="hidden" name="forgot_pass_Sbumit" value="kv_yes" >
 	<input type="submit" class="btn btn-primary" value="Get Password" > 
 </form>

The above form will be our reset form. Let’s write the php handler code for this form .

if(isset($_POST['forgot_pass_Sbumit'])) {
      //Here our code for reset.
}

Now, we need to get the variable value and format it.

 if ( isset($_POST['emailToreceive']) && empty($_POST['emailToreceive']) )
 	$errors['userName'] = __("<strong>ERROR</strong>: Username/e-mail Shouldn't be empty.");
 else{
 	$emailToreceive = $_POST['emailToreceive']; 
 	$user_input = esc_sql(trim($emailToreceive));
}

Check Whether the user entered the email or his/her password with help of below code.

if ( strpos($user_input, '@') ) {
 	$user_data = get_user_by( 'email', $user_input ); 
 	if(empty($user_data) ) {
 		$errors['invalid_email'] = 'Invalid E-mail address!'; 
 	}
} else {
 	$user_data = get_user_by( 'email', $user_input ); 
 	if(empty($user_data) ) { 
 		$errors['invalid_usename'] = 'Invalid Username!'; 
 	}
}

The User entered Input Validated here, if its not original, than we will show them an error and left other tasks. Otherwise, we will continue the below one.

if(empty($errors)) { 
  	if(kv_forgot_password_reset_email($user_data->user_email)) {
  	 	$success['reset_email'] = "We have just sent you an email with Password reset instructions.";
  	} else {
  	 	$errors['emailError'] = "Email failed to send for some unknown reason."; 
  	} //emailing password change request details to the user 
 }

We will call a custom function to make it working. If the function returns true, Than it will sent a reset email to user. otherwise, some problem in reset email. Let’s see the reset function. You can place this function on your theme `functions.php` or your plugin main file.

function kv_forgot_password_reset_email($user_input) {
 	global $wpdb; 
 	$user_data = get_user_by( 'email', $user_input ); 
 	$user_login = $user_data->user_login;
	 $user_email = $user_data->user_email;
 
 	$key = $wpdb->get_var("SELECT user_activation_key FROM $wpdb->users WHERE user_login ='".$user_login."'");
 	if(empty($key)) {
 	//generate reset key
		 $key = wp_generate_password(20, false);
		 $wpdb->update($wpdb->users, array('user_activation_key' => $key), array('user_login' => $user_login));
	 }
 
 	$message = __('Someone requested that the password be reset for the following account:') . "<br><br><br>";
 	$message .= get_option('siteurl') . "<br><br>";
 	$message .= sprintf(__('Username: %s'), $user_login) . "<br><br><br>";
 	$message .= __('If this was a error, just ignore this email as no action will be taken.') . "<br><br>";
 	$message .= __('To reset your password, visit the following address:') . "<br><br>";
 	$message .= '<a href="'.tg_validate_url() . "action=reset_pwd&key=$key&login=" . rawurlencode($user_login) . '" > '.tg_validate_url() . "action=reset_pwd&key=$key&login=" . rawurlencode($user_login) ."</a><br><br>";

 	if ( $message && !wp_mail($user_email, 'Password Reset Request', $message) ) {
 	$msg = false ; 
 	}
	 else $msg = true; 

 	return $msg ; 
}

Now, the reset email sent to user, when the user click the verification link, we need to verify it. and create a new password and we have to email them back.we will write the below code on the same rest login page.

if(isset($_GET['key']) && $_GET['action'] == "reset_pwd") { 
	 $reset_key = $_GET['key'];
	 $user_login = $_GET['login'];
 	$user_data = $wpdb->get_row("SELECT ID, user_login, user_email FROM $wpdb->users WHERE user_activation_key = '".$reset_key."' AND user_login = '". $user_login."'");
	 $user_login = $user_data->user_login;
	 $user_email = $user_data->user_email;
	 if(!empty($reset_key) && !empty($user_data)) {
		 if ( kv_rest_setting_password($reset_key, $user_login, $user_email, $user_data->ID) ) {
			 $errors['emailError'] = "Email failed to sent for some unknown reason"; 
		 }
		 else {
 			$redirect_to = get_site_url()."/login?action=reset_success";
 			wp_safe_redirect($redirect_to);
 			exit();
		 }
	 }
 	else exit('Not a Valid Key.'); 
 }

From the above code, we have a calling function, which will handle the new password generation and it will email to the requested user. Let’s see the function code

function kv_rest_setting_password($reset_key, $user_login, $user_email, $ID) {
 
  	$new_password = wp_generate_password(7, false); //you can change the number 7 to whatever length needed for the new password
 	 wp_set_password( $new_password, $ID ); //mailing the reset details to the user
 
  	$message = __('Your new password for the account at:') . "<br><br>";
 	 $message .= get_bloginfo('name') . "<br><br>";
 	 $message .= sprintf(__('Username: %s'), $user_login) . "<br><br>";
  	$message .= sprintf(__('Password: %s'), $new_password) . "<br><br>";
 	 $message .= __('You can now login with your new password at: ').'<a href="'.get_option('siteurl')."/login" .'" >' . get_option('siteurl')."/login" . "</a> <br><br>";

  	if ( $message && !wp_mail($user_email, 'Your New Password to login into eimams', $message) ) {
  	 	$msg = false; 
 	 } else {
  	 	$msg = true; 
  	 	$redirect_to = get_site_url()."/login?action=reset_success";
  	 	wp_safe_redirect($redirect_to);
  	 	exit();
  	} 

  	return $msg; 
}

I forget to provide the tg_validate_url function. Here is the update of program

################################################################################
// Validate the url
################################################################################
function tg_validate_url() {
	global $post;
	$page_url = esc_url(get_permalink( $post->ID ));
	$urlget = strpos($page_url, "?");
	if ($urlget === false) {
		$concate = "?";
	} else {
		$concate = "&";
	}
	return $page_url.$concate;
}

I hope you like this article about how to create a custom page with custom password resetting option. If you are interested to follow me on social site, Use the below things to follow me there and get more articles.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

2 comments

  1. commenter

    All I get is Fatal error: Call to undefined function tg_validate_url() in functions.php

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.

Advertisement

Category Posts