Show Error Message On WordPress Custom Login Template Page
Posted by in Tips And Tricks July 15, 2011 8 Comments

“How can I prevent the page to be redirected to /wp-login.php if a wrong password is entered ? (I’d rather prefer to have an error message appear in the form itself)”. That’s a very good question of weridrubikscube

From the tutorial: How to Add WordPress Login Form On Sidebar Or Custom Page, we have 2 sections:

  • 1. Add the login form on Sidebar
  • 2. Add login form on a Custom template page

Today, let focus on section 2, I’ll give you some instructions and new source code for the Custom Login Page.

First of all, you may need to know How to create a new WordPress template page.

As we’re going to show error message without redirecting to wp-login.php so I suggest we use Ajax to post data. Therefore, your template is required to load the jQuery script some where in the header.php file (in the root of your template’s directory)

header.php:

....
<head>
 
....
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"><!--mce:0--></script>
....
 
</head>
....

After that, let create a new file in your Theme directory (ex: page-login-error-message.php) and add following codes:

<?php
/*
Template Name: Login With Error Message
*/
?>
<?php
	global $user_ID;
	if (!$user_ID)
	{
		if($_POST)
		{
			$username = $wpdb->escape($_REQUEST['log']);
			$password = $wpdb->escape($_REQUEST['pwd']);
			$remember = $wpdb->escape($_REQUEST['rememberme']);
 
			if($remember) $remember = "true";
			else $remember = "false";
			$login_data = array();
			$login_data['user_login'] = $username;
			$login_data['user_password'] = $password;
			$login_data['remember'] = $remember;
			$user_verify = wp_signon( $login_data, true );
 
			if ( is_wp_error($user_verify) ) 
			{
				echo "<span style='color:#FF0000'>Invalid username or password. Please try again!</span>";
				exit();
			} 
			else 
			{	
				echo "<script type='text/javascript'>window.location='". get_bloginfo('url') ."'</script>";
				exit();
			}
		}
	}
?>
<?php
	get_header(); 
?>
 
		<div id="container">
			<div id="content" role="main">
<?php 
	if(!is_user_logged_in())
	{
?>     
<div id="result" style="color:#FF0000"></div>   
<form name="login" method="post" id="wp_login_form" action="<?php echo get_option('home'); ?>/wp-login.php">
	<input type="hidden" name="action" value="login" />
	<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
	<table width="450px" border="0" cellpadding="0" cellspacing="0">
	  <tr>
		<td colspan="2" style="padding-bottom: 8px;"><strong>MEMBER LOGIN</strong></td>
	  </tr>
	  <tr>
		<td><strong>Username:</strong></td>
		<td align="right"><input type="text" name="log" id="log" value="" class="text" /></td>
	  </tr>
	  <tr>
		<td><strong>Password:</strong></td>
		<td align="right"><input type="password" name="pwd" id="pwd" class="text" /></td>
	  </tr>
	  <tr>
		<td align="left" colspan="2"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</td>
	  </tr>
	  <tr>
		<td align="left" colspan="2"><input type="submit" id="btnsubmit" value="Login"/></td>
	  </tr>
	  <tr>
		<td align="left" colspan="2"><a href="<?php echo get_option('home'); ?>/forgot-password/">[Forgot password?]</a> </td>
	  </tr>
 
	</table>
</form>
<script type="text/javascript">  						
$("#btnsubmit").click(function() 
{
	$('#result').html('Loading ...').fadeIn();
	var input_data = $('#wp_login_form').serialize();
	$.ajax({
		type: "POST",
		url:  "<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>",
		data: input_data,
		success: function(msg){
			$('#result').html(msg);
		}
	});
	return false;
});
</script>	
<?php 
	}
	else
	{
		global $current_user;
		get_currentuserinfo();
		if($current_user->user_firstname != '' && $current_user->user_lastname)
			echo "Welcome " . $current_user->user_firstname . "," . $current_user->user_lastname . "!";
		else
			echo "Welcome " . $current_user->user_login . "!";
 
		echo " | <a title='Logout' href='" . wp_logout_url('index.php') . "'>Logout</a><br><br>"; 
?>
          You are currently logged in!
<?php 
	}
?>
			</div><!-- #content -->
		</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
  • Line: 75 .. 91: we’re using jQuery Ajax to submit data to verify the login detail (Username/Password) then process the result.
  • Line: 06 .. 36: validate data and verify the login request then return result for the Ajax callback function.
WordPress Login Form On Custom Page

WordPress Login Form On Custom Page

The form is look like with the one on the last tutorial. However, when you click Login button with wrong pair of Username and Password, the magic will occur:

WordPress Custom Login Page With Ajax Error Message

WordPress Custom Login Page With Ajax Error Message

An error message appears in Red in the form without redirecting to wp-login.php page or refresh page.

Download the Login With Error Message Template source code.

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • http://www.sampletemplates.org/ Sample template

    You made my smile, thanks for the helpful stuff! @bose

  • http://tepurubaseball.co.nz webladynz

    I am working on my local development site. I have created the page and when I preview it is tells me I am logged in. When I login from the login block on my sidebar with an invalid user name or password I am still directed to wp-login.php. What am I missing.

    Login
    Register
    Forgot?

    Success!
    Check your email for the password and then return to log in.

    Success!
    Check your email to reset your password.

    Have an account?
    Log in or sign up! It’s fast & free!

    <form method="post" action="/wp-login.php” class=”wp-user-form”>

    :
    <input type="text" name="log" value="” size=”20″ id=”user_login” tabindex=”11″ />

    :

    Remember me

    <input type="submit" name="user-submit" value="” tabindex=”14″ class=”user-submit” />
    <input type="hidden" name="redirect_to" value="” />

    Register for this site!
    Sign up now for the good stuff.
    <form method="post" action="” class=”wp-user-form”>

    :
    <input type="text" name="user_login" value="” size=”20″ id=”user_login” tabindex=”101″ />

    :
    <input type="text" name="user_email" value="” size=”25″ id=”user_email” tabindex=”102″ />

    <input type="submit" name="user-submit" value="” class=”user-submit” tabindex=”103″ />
    <?php $register = $_GET['register']; if($register == true) { echo 'Check your email for the password!’; } ?>
    <input type="hidden" name="redirect_to" value="?register=true” />

    Lose something?
    Enter your username or email to reset your password.
    <form method="post" action="” class=”wp-user-form”>

    :

    <input type="submit" name="user-submit" value="” class=”user-submit” tabindex=”1002″ />
    <?php $reset = $_GET['reset']; if($reset == true) { echo 'A message will be sent to your email address.’; } ?>
    <input type="hidden" name="redirect_to" value="?reset=true” />

    Welcome,

    ID, 60); ?>

    You’re logged in as

    <a href="”>Log out |
    <?php if (current_user_can('manage_options')) {
    echo '‘ . __(‘Admin’) . ‘‘; } else {
    echo ‘‘ . __(‘Profile’) . ‘‘; } ?>

    • hoanhuynh

      Hi,
      Can you send me your working file as it’s easier for me be able to help.
      Thanks,
      H2.

      • http://tepurubaseball.co.nz webladynz

        Hi

        I have sent it

        • hoanhuynh

          It seems that you did not include JQuery script in the header.php file that I already mentioned in the first section of this post.

          Please try to add this line in your header.php file (in the root of your template’s directory):

          ……….
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js&quot; type="text/javascript"></script>
          ……….

          Let me know how it’s going.
          Good luck!

  • John Tim

    Very nice thnx dude on more qustion i have try to get same for forget password error but its not help can u helb me i have use this code but it get syntax errors :

    [CODE]
    <form method="post" action="” class=”wp-user-form”>
       
            :
           
       
       
           
            <input type="submit" name="user-submit" value="” class=”user-submit” tabindex=”1002″ />
    <?php if (isset($_POST['reset_pass'])){
        global $wpdb;
        $username = trim($_POST['user_login']);
        $user_exists = false;
        if ( username_exists( $username ) ){
            $user_exists = true;
            $user_data = get_userdatabylogin($username);
        }elseif{
            if ( email_exists($username) ){
                $user_exists = true;
                $user = get_user_by_email($username);
            }
        }else{
            $error[] = '’.__(‘Username or Email was not found, try again!’).”;
        }
        if {$user_exists){
            $user_login = $user->user_login;
            $user_email = $user->user_email;
            // Generate something random for a password… md5′ing current time with a rand salt
            $key = substr( md5( uniqid( microtime() ) ), 0, 8);
            // Now insert the new pass md5′d into the db
            $wpdb->query(“UPDATE $wpdb->users SET user_activation_key = ‘$key’ WHERE user_login = ‘$user_login’”);
            //create email message
            $message = __(‘Someone has asked to reset the password for the following site and username.’) . “rnrn”;
            $message .= get_option(‘siteurl’) . “rnrn”;
            $message .= sprintf(__(‘Username: %s’), $user_login) . “rnrn”;
            $message .= __(‘To reset your password visit the following address, otherwise just ignore this email and nothing will happen.’) . “rnrn”;
            $message .= get_option(‘siteurl’) . “/wp-login.php?action=rp&key=$keyrn”;
            //send email meassage
            if (FALSE == wp_mail($user_email, sprintf(__(‘[%s] Password Reset’), get_option(‘blogname’)), $message)
            $error[] = ” . __(‘The e-mail could not be sent.’) . “n” . __(‘Possible reason: your host may have disabled the mail() function…’) . ”;
        }
        if (count($error) > 0 ){
            foreach($error as $e){
                echo $e . ;
            }
        }else{
            echo ”.__(‘A message will be sent to your email address.’).”;
        }}?>
           
           
        [/CODE]but this get syntax errors error
     

    • http://4rapiddev.com/ Hoan Huynh

      Hi There,

      Not sure what made changes but please send to source file in order for me can take a look.

      Thank you,
      H2.

  • http://www.robsteele.co.uk/ Website design Loughborough

    cool post man