Ahmad Awais

NAVIGATE


SHARE


How to Create a Front-End Login Page in WordPress

Ahmad AwaisAhmad Awais

WordPress as we know it, is not just a blogging tool, it is a CMS (Content Management System). Most of the freelancers out there use WordPress to build custom sites to entertain requirement friendly behavior. Even a basic CMS based project in WordPress demands for a custom login page in WordPress. Today I intend to discuss how one can create a custom login page in WordPress.

JUST A NOTE!
👨‍💻 I’m teaching thousands of devs how to become VSCode Power Users
✅ This site is super fast?! It’s hosted with Kinsta on Google servers →

Create a Custom WordPress Page#

First of all create a custom page in the root folder of your WordPress theme and name it aa_login.php (I use aa_ to make my code unique, it is a kind of abbreviation of my name Ahmad Awais). At the top of the page write the comment of Template Name:, a PHP comment, so that WordPress can recognize this custom page.

Using $user_login#

$user_login is a global variable which helps us find the present user login data. With which we can easily find out about the following activity of a particular user.

Check if Login Failed#

If user tries to login with wrong credentials, WordPress will return a query string ?login=failed. This will in turn be used to display an error message.

Check if User Is Already Logged In#

Then I used is_user_logged_in() function to check if the user is already logged in. So, if an already logged in user tends to revisit the login page, he’ll get a message about returning home or logging out. There is no sense in displaying the login form to an already logged in user.

Else Display the Login Form#

In this part I used wp_login_form() function with some arguments to display the contact form. Here you need to pay attention to the particular argument ‘redirect’ => home_url(‘/wp-admin/’), this is basically redirecting user after login to home_url(‘path-here’). You can easily change the path to redirect a user to another page E.g. a custom front-end dashboard.

Live Example#

Don’t forget to publish the page from admin panel Pages > Add New > Select the template name.

What’s good is a code without demo? Here is a live example

Live Demo

Full Code#

 

JUST A NOTE!
👨‍💻 I’m teaching thousands of devs how to become VSCode Power Users
✅ This site is super fast?! It’s hosted with Kinsta on Google servers →

I help businesses understand developers 📟 Just launched Node.js CLI Automation Course 👨‍🏫 Edutainer at VSCode.pro 🎩 An award-winning GitHub Star open-source engineer & advocate 🦊 Google Developers Expert Web DevRel 🌳 Node.js foundation Community Committee Outreach Lead ✌️ Author of various open-source dev-tools and software libraries used by millions of developers worldwide ⓦ WordPress Core Developer 📣 TEDx Speaker 🙌 Leading developers and publishing technical content for over a decade 💜 Loves his wife (Maedah) ❯ Learn more →

Say 👋 on Twitter @MrAhmadAwais | Subscribe to the Developers Takeaway!

📨

Developers Takeaway

Takeaway my professional opinion on open-source, developer relations, growing your business with family, and everything in between! Delivered to your inbox a couple of times every year. I'm even funny at times. I hate spam — pinky-promise!

👨‍💻👩‍💻 118,947 Developers Already Subscribed
Comments 34
  • Uneeb Ahmad
    Posted on

    Uneeb Ahmad Uneeb Ahmad

    Reply Author

    Awesome (Y)


  • teerapuch
    Posted on

    teerapuch teerapuch

    Reply Author

    Thank You!
    It clean for Beginner


  • Daniel
    Posted on

    Daniel Daniel

    Reply Author

    Weird issue. On your demo, if you type the login details wrong, you get redirected back to your custom login page. When I did everything as you have done above, then when the login credentials are wrong on my site, I end up getting redirected to the wp-login.php page.

    What have I done wrong?


    • AhmadAwais
      Posted on

      AhmadAwais AhmadAwais

      Reply Author

      There are several checks for that. E.g.

      add_action( ‘wp_login_failed’, ‘aa_login_failed’ ); // hook failed login

      function aa_login_failed( $user ) {
      // check what page the login attempt is coming from
      $referrer = $_SERVER[‘HTTP_REFERER’];

      // check that were not on the default login page
      if ( !empty($referrer) && !strstr($referrer,’wp-login’) && !strstr($referrer,’wp-admin’) && $user!=null ) {
      // make sure we don’t already have a failed login attempt
      if ( !strstr($referrer, ‘?login=failed’ )) {
      // Redirect to the login page and append a querystring of login failed
      wp_redirect( $referrer . ‘?login=failed’);
      } else {
      wp_redirect( $referrer );
      }

      exit;
      }
      }


      • Martijn
        Posted on

        Martijn Martijn

        Reply Author

        Hi,

        I know it is a long time ago, but I was trying to implement this.
        Awesome post, very clearly explained. And it is working for most part.

        But the failed login, will send me to the wp-admin login.
        I used the code above, which makes sense with the referer. (try to not blindly copy/past, but first understand what is written)
        But it doesn’t seem to work.

        Any clues why this might be?


  • SadyeMetzler36
    Posted on

    SadyeMetzler36 SadyeMetzler36

    Reply Author

    Awesome blog! Do you have any tips and hints for aspiring writers? I’m hoping to start my own site soon but I’m a little lost on everything. Would you advise starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m completely overwhelmed .. Any suggestions? Cheers!


    • Ahmad Awais
      Posted on

      Ahmad Awais Ahmad Awais

      Reply Author

      If you want to write just head over to Medium.com and start writing for free. Then see how it goes from there.


  • AnnabelleOaks97
    Posted on

    AnnabelleOaks97 AnnabelleOaks97

    Reply Author

    Just want to say your article is as astounding. The clearness in your post is just nice and i could assume you are an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.


    • Ahmad Awais
      Posted on

      Ahmad Awais Ahmad Awais

      Reply Author

      I’m glad you enjoyed reading it. I’m planning to post a series of articles about using WordPress as an App. Which means front-end registration and a custom dashboard. BTW you can subscribe to my the Newsletter, and get an email whenever I publish an article.


  • MelvinaHalford
    Posted on

    MelvinaHalford MelvinaHalford

    Reply Author

    Greate pieces. Keep writing such kind of information on your site. Im really impressed by it.
    You have performed an excellent job. I will definitely digg it and individually suggest to my friends. I am confident they’ll be benefited from this web site.


  • khubbaib
    Posted on

    khubbaib khubbaib

    Reply Author

    wp_login_form($args); at this place you passed $args which is defined after that…. please correct the code.


    • Ahmad Awais
      Posted on

      Ahmad Awais Ahmad Awais

      Reply Author

      I just updated the code. It works either way, but it’s always good to follow standards.


  • sam
    Posted on

    sam sam

    Reply Author

    hi this is nice post. but i am create login page and i want to logged in user through login but user does not redirect to admin area.
    so what can i do so user redirect to admin area.
    here is my code
    if($_POST) {

    global $wpdb;

    //We shall SQL escape all inputs
    $username = $wpdb->escape($_REQUEST[‘username’]);
    $password = $wpdb->escape($_REQUEST[‘password’]);
    $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’] = “true”;
    $redirect_to = admin_url();
    $requested_redirect_to = $redirect_to;
    $user_verify = wp_signon( $login_data, true);
    if ( is_wp_error( $user_verify ) ) {
    echo $user_verify->get_error_message();
    }

    $user = get_user_by(‘ID’, $user_verify->ID);
    $user_id = $user_verify->data->ID;
    if($user) {
    wp_set_current_user($user_id, $user->user_login);
    wp_set_auth_cookie($user_id);
    do_action( ‘wp_login’, $user->user_login );
    }
    if ( is_wp_error($user) ) {
    header(“Location: ” . home_url() . “/login/error/”);
    // Note, I have created a page called “Error” that is a child of the login page to handle errors. This can be anything, but it seemed a good way to me to handle errors.
    }
    else {
    //wp_safe_redirect(admin_url());
    echo “window.location='”. home_url( ‘/wp-admin/’ ) .”‘”;
    exit();
    }
    }
    else {

    // No login details entered – you should probably add some more user feedback here, but this does the bare minimum
    echo “Invalid login details”;
    }

    <form id="login" name="form" action="/custom-login/” method=”post”>


  • Huzaifah
    Posted on

    Huzaifah Huzaifah

    Reply Author

    Hello Ahmed.

    Im having some issues using this script of yours. I have followed all the steps and installed it fine, however a couple of issues.

    1. If there is an error in the login, it takes you to /wp-admin
    2. When you logout, it takes you to /wp-admin
    3. If you go the the login page when you are logged in, is there someway it can redirect you to the redirect URL instead of showing the message hello User, you are already logged in?

    Im not good with PHP so bear with me. Jzk


    • Ahmad Awais
      Posted on

      Ahmad Awais Ahmad Awais

      Reply Author

      The code I wrote, is not meant for the three things mentioned here. Sure, this can be done, will write about that :)


  • Joseph
    Posted on

    Joseph Joseph

    Reply Author

    Thank you very much for taking the time to write and share this code.

    Your post is a few years old but there are not many (any?) other wp experts sharing code for front-end login……so this is still very helpful even years later.

    Like other commenters I have the same behaviour – eg If there is an error in the login, it takes you to /wp-admin.

    So if you could make the time to write about that, that would be great.

    Also if you have any sources of info for writing code for registration on front end, lost password, that would be appreciated.


    • Ahmad Awais
      Posted on

      Ahmad Awais Ahmad Awais

      Reply Author

      Glad I could help Joseph! I have decided to build a small video series on everything you asked for. Subscribe at https://WPTakeaway.club to know more when I launch it.


  • Mohammad Kashif
    Posted on

    Mohammad Kashif Mohammad Kashif

    Reply Author

    Hi
    Thanks so much for clean and clear tutorial.
    How can i add Forgot Password and Registration links?

    Thanks


  • Rami
    Posted on

    Rami Rami

    Reply Author

    Hello Ahmed and thanks for this clear code,,

    can I customize the login form? for example, can I add social login right above the username text field?


    • Rami
      Posted on

      Rami Rami

      Reply Author

      One more things, I am using app maker for my wordpress site, this app maker allow me to write HTML code directly, Can I make HTML code for the login form and when I hit the submit button it will be sign in directly based on the back-end code?

      I hope my problem clear enough


      • Rami
        Posted on

        Rami Rami

        Reply Author

        I am using app maker for my wordpress site, this app maker allow me to write HTML code directly, Can I make HTML code for the login form and when I hit the submit button it will be sign in directly based on the back-end code?

        I hope my problem clear enough


  • srimongol.com
    Posted on

    srimongol.com srimongol.com

    Reply Author

    nice


  • Patje
    Posted on

    Patje Patje

    Reply Author

    Is this something that can be solved?

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘disable_embeds_rewrites’ not found or invalid function name in \wp-includes\class-wp-hook.php on line 286

    Thanks for the awesome code anyway keep up the goodwork!


  • Ashwini
    Posted on

    Ashwini Ashwini

    Reply Author

    Hello
    Thanks tutorial this helped me a lot.
    But i have one query,how can i add Forgot Password and Registration links with the same as in demo?
    I also Subscribed to Takeaway but haven’t got any link regarding this, please suggested.

    Thanks


  • sharad
    Posted on

    sharad sharad

    Reply Author

    can you share the complete code of this with signup and forget pawword


  • mohammad
    Posted on

    mohammad mohammad

    Reply Author

    not work as well as demo !!!
    details wrong = wp-login.php
    but demo is different


  • Dani
    Posted on

    Dani Dani

    Reply Author

    Hello,

    I really appreciate your work ! The code works perfectly, I could redirect users to a custom page with controlled access after log in.

    I just encounter a problem, when I change the redirect of the log out loop to the home page, it doesn’t log out… Is there a way to do that ? Or redirect to a page that confirms the log out while effectively doing it ? The original script redirects to the worpress log in and it doesn’t look good with the rest.

    Thanks in advance ! :)


  • Federica
    Posted on

    Federica Federica

    Reply Author

    Hello and thanks for code. I have a problem. Everytime if i try to login first time on form work succesuf after (logout, delete cache and retry to login) if i try other time i have a redirect problem becouse continue to redirect to me in same page (i have put the login form on home page).

    How can we fix it?


  • lois
    Posted on

    lois lois

    Reply Author

    How do i style this form


  • tharun
    Posted on

    tharun tharun

    Reply Author

    hello sir can you help how to create custom website user login with custom php code no plugin!.


  • Echo
    Posted on

    Echo Echo

    Reply Author

    Great job with this. Do you have a Registration one too? Do you favor Ajax when having Login and Registration on same page? I ask only because I feel bots can’t find the registration then.