If you are in this tutorial that means you want to get rid of WordPress’s boring user registration form !

No worries you are at absolutely right place for getting your solution. We will explore in this tutorial how to handle custom user registration in wordpress without using WordPress’s default registration form which is present generally at yoursitename.com/wp-login/?action=register

Follow the below mentioned steps:

1. Make a custom HTML form

First of all, we have to make a custom html form in order to get user’s input. So we will make it with all the fields desired for example, first name, last name, email, password etc.


<div class="form-wrapper">

<h2 class="register-heading"><?php _e( 'Sign Up', 'debate' ); ?></h2>

<div id="error-message"></div>

<form method="post" name="st-register-form">

 <div class="form-label"><label for="st-username"><?php _e( 'Username', 'debate' ); ?></label></div>
 <div class="field"><input type="text" autocomplete="off" name="username" id="st-username" /></div>

<div class="form-label"><label for="st-email"><?php _e( 'Email', 'debate' ); ?></label></div>
 <div class="field"><input type="text" autocomplete="off" name="mail" id="st-email" /></div>

<div class="form-label"><label for="st-psw"><?php _e( 'Password', 'debate' ); ?></label></div>
 <div class="field"><input type="password" name="password" id="st-psw" /></div>

 <div class="form-label"><label for="st-fname"><?php _e( 'First Name', 'debate' ); ?></label></div>
 <div class="field"><input type="text" autocomplete="off" name="fname" id="st-fname" /></div>

<div class="form-label"><label for="st-lname"><?php _e( 'Last Name', 'debate' ); ?></label></div>
 <div class="field"><input type="text" autocomplete="off" name="lname" id="st-lname" /></div>

<div class="frm-button"><input type="button" id="register-me" value="Register" /></div>

</form>

</div>

We can place this form anywhere we desire like in widget, template etc.

By default WordPress provides only three fields for registration that is username, email and password, so here we have two extra fields first name and last name. We will see further how to save these extra fields during registration process.

2. Write ajax submission code for form.


/* Registration Ajax */
 jQuery('#register-me').on('click',function(){

var action = 'register_action';

var username = jQuery("#st-username").val();
 var mail_id = jQuery("#st-email").val();
 var firname = jQuery("#st-fname").val();
 var lasname = jQuery("#st-lname").val();
 var passwrd = jQuery("#st-psw").val();

var ajaxdata = {

action: 'register_action',
 username: username,
 mail_id: mail_id,
 firname: firname,
 lasname: lasname,
 passwrd: passwrd,

};

jQuery.post( ajaxurl, ajaxdata, function(res){ // ajaxurl must be defined previously

jQuery("#error-message").html(res);
 });
 });

Add above code to your theme’s js file. Note that ajaxurl must be define previously, if not you can do so by adding following code to your functions.php


function st_ajaxurl(){ ?>

<script>

var ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';

</script>

}
add_action('wp_head','st_ajaxurl');

3.Handle Registration and validations

This is the most important step as in this step we will be doing all the validations and will be inserting a new user to the database. We will use wordpress ajax for handling this part, you can check how wordpress ajax works in my previous tutorial Using ajax in wordpress.
Add follwing code to your functions.php file.


function st_handle_registration(){

if( $_POST['action'] == 'register_action' ) {

$error = '';

$uname = trim( $_POST['username'] );
 $email = trim( $_POST['mail_id'] );
 $fname = trim( $_POST['firname'] );
 $lname = trim( $_POST['lasname'] );
 $pswrd = $_POST['passwrd'];

if( empty( $_POST['username'] ) )
 $error .= '<p class="error">Enter Username</p>';

if( empty( $_POST['mail_id'] ) )
 $error .= '<p class="error">Enter Email Id</p>';
 elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
 $error .= '<p class="error">Enter Valid Email</p>';

if( empty( $_POST['passwrd'] ) )
 $error .= '<p class="error">Password should not be blank</p>';

if( empty( $_POST['firname'] ) )
 $error .= '<p class="error">Enter First Name</p>';
 elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
 $error .= '<p class="error">Enter Valid First Name</p>';

if( empty( $_POST['lasname'] ) )
 $error .= '<p class="error">Enter Last Name</p>';
 elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
 $error .= '<p class="error">Enter Valid Last Name</p>';

if( empty( $error ) ){

$status = wp_create_user( $uname, $pswrd ,$email );

if( is_wp_error($status) ){

$msg = '';

 foreach( $status->errors as $key=>$val ){

 foreach( $val as $k=>$v ){

 $msg = '<p class="error">'.$v.'</p>';
 }
 }

echo $msg;

 }else{

$msg = '<p class="success">Registration Successful</p>';

 echo $msg;
 }

}
 else{

echo $error;
 }
 die(1);
 }
}
add_action( 'wp_ajax_register_action', 'st_handle_registration' );
add_action( 'wp_ajax_nopriv_register_action', 'st_handle_registration' );

In above step first we are validating all the data; if error is present it will return the error which will be shown to user in error-message div of our HTML form. If everything is fine we are going to register user using wp_create_user function this function accepts three parameters viz. username, password and email of the user. But what about the first name and last name we will be dealing this fields in next step.
Note that wp_create_user will return the user id of newly created user.

4. Save Metadata of the user

WordPress provides two hooks namely user_register which is triggered whenever any new user gets created and profile_update which is triggered whenever existing user’s profile is updated. We will use these hooks to save metadata of the user. user id will be passed as parameter to the callback function which is which is hooked to these actions.


&nbsp;

function user_metadata( $user_id ){

if( !empty( $_POST['firname'] ) && !empty( $_POST['lasname'] ) ){

update_user_meta( $user_id, 'first_name', trim($_POST['firname']) );
 update_user_meta( $user_id, 'last_name', trim($_POST['lasname']) );
 }

 update_user_meta( $user_id, 'show_admin_bar_front', false );
}
add_action( 'user_register', 'user_metadata' );
add_action( 'profile_update', 'user_metadata' );

In this way you can add any amount of metadata in the form and can save accordingly.

So we have looked over how to handle custom user registration process in wordpress. It is very simple and flexible too. Proper usage of actions and filters makes life easy of a wordpress programmer 🙂

If you have any queries or suggestions your comments are always welcome from sharethingz team. 🙂

Custom user registration in wordpress using ajax

58 thoughts on “Custom user registration in wordpress using ajax

    • October 29, 2013 at 12:20 pm
      Permalink

      Thank you Koen 🙂

      Reply
  • October 26, 2013 at 12:25 pm
    Permalink

    I have tried the steps given by you but that are not working

    Reply
    • October 29, 2013 at 12:18 pm
      Permalink

      What error you are getting there ?

      Reply
  • November 20, 2013 at 11:55 am
    Permalink

    in JS just use jQuery(‘#st-register-form’).serialize() and add hidden input form element:

    Reply
    • December 8, 2013 at 4:12 pm
      Permalink

      Thank you Slammer for your valuable suggestion, we can surely serialize the form data for submitting the form.

      I have used this method just to get readability for the newbies 🙂

      Reply
  • December 16, 2013 at 4:26 pm
    Permalink

    Nice article but I wanted to get something like this, “http://www.shoutmeloud.com/wp-login.php?action=register”.
    Any comments?

    Reply
    • January 28, 2014 at 5:14 am
      Permalink

      Hi Dexter you’d have to have your registration page customized, this code is also meant to be used outside the main WordPress registration form. If you’d like one customized and help getting this installed drop me a line http://bit.ly/UHR2WS

      Reply
  • February 18, 2014 at 12:40 pm
    Permalink

    but how i can customize it on : site.com/wp-login.php?action=register !!
    here where i want to make the changes !

    Reply
  • March 11, 2014 at 8:26 am
    Permalink

    I’m a bit confused… Is it necessary to manually save first and last name on profile updates? I thought it was only necessary for registration (‘user_register’) :s

    Reply
    • March 11, 2014 at 1:04 pm
      Permalink

      Hi Panos,

      Yes it is necessary, because user_register only works for first time when user registers himself on website. If he updates his information like first name and last name it should be updated which is done on “profile_update” action.
      Since first name and last name are stored in user meta table of WordPress site, it needs to be updated using these actions. 🙂

      Reply
  • March 11, 2014 at 1:42 pm
    Permalink

    Hm… I understand the difference between the two actions and I can see why it is necessary to save the metadata upon user registration. But WordPress provides a “first name” and a “last name” filed in the user account page. So I guess that is saves them upon update… Sorry for insisting 🙂

    Reply
    • March 11, 2014 at 7:07 pm
      Permalink

      Yes that is also right ! 😉

      Reply
  • March 17, 2014 at 10:54 pm
    Permalink

    Does using admin-ajax.php (ajaxurl) secure ?
    I want to avoid using POST password because it is not safe at all, and I can’t find anything about ssl using ajax with wordpress.

    Reply
    • March 19, 2014 at 6:51 am
      Permalink

      Yes it is absolutely safe.

      Reply
  • March 25, 2014 at 12:25 pm
    Permalink

    When we use user approve plugin then login not functional….any solution

    Reply
    • March 26, 2014 at 4:59 pm
      Permalink

      Please ask this question in plugin’s support forum.

      Reply
  • April 26, 2014 at 12:56 pm
    Permalink

    Please help i added extra fields on jquery its not working,i can i customize this.

    Reply
  • April 26, 2014 at 12:57 pm
    Permalink

    Please help i added extra fields on jquery its not working,how can i customize the above code.

    Reply
    • May 19, 2014 at 4:21 am
      Permalink

      Hi Rajesh,

      Sorry for delay in reply. Which field you want to add ? You can add in the same way like demonstrated in tutorial above.

      Reply
  • June 16, 2014 at 10:28 am
    Permalink

    Is the form able to send a confirmation email to the registered user given them their login details?

    Reply
    • June 25, 2014 at 11:15 am
      Permalink

      Currently not but we can do so by using user_register hook of WordPress.

      Reply
  • July 30, 2014 at 3:28 am
    Permalink

    All is working aside from the user meta. It does not save the data in the profile. Any idea why?

    Reply
    • July 30, 2014 at 6:47 am
      Permalink

      Hello,

      This is tested code and working properly. Please send me your code snippet so that I will be able to help you out.

      Thanks for reading article. 🙂

      Reply
  • August 9, 2014 at 3:43 pm
    Permalink

    HI Ankit,

    Could you pls help me with the step wise file names where I need to place the code?

    Reply
    • August 10, 2014 at 2:33 pm
      Permalink

      Hi Pawan,

      Only the code in step 1 in above post will go on whichever template you want to render the registration form.

      Rest of the code you can add to your theme’s functions.php file and it should work fine.
      Let me know if this works for you.

      Reply
  • August 30, 2014 at 12:20 am
    Permalink

    How about security issues for this form? Will this form be secure? What about nonce?

    Reply
    • August 30, 2014 at 2:10 pm
      Permalink

      Hi Chris,

      You are right, we can add nonce to make this one more secure. As I mentioned in my previous comment, this article was intended for newbies in WordPress, I kept it more simple. I will update to article soon. Thanks for pointing out.

      Cheers ! 🙂

      Reply
  • September 22, 2014 at 9:30 pm
    Permalink

    It’s difficult to find well-informed people on this subject,
    however, you seem like you know what you’re talking about!
    Thanks

    Reply
    • September 23, 2014 at 6:29 am
      Permalink

      Thank you for your kind words. Keep visiting blog 🙂

      Reply
  • September 28, 2014 at 8:37 pm
    Permalink

    This excellent website really has all the information I needed about this subject and didn’t know who to ask.

    Reply
  • November 14, 2014 at 12:35 am
    Permalink

    Woah! I’m really igging the template/theme of this blog.
    It’s simple, yet effective. A lot of times it’s very difficult to get that
    “perfect balance” between superb usability
    and visual appearance. I must say you have done a amazing job
    wiith this. In addition, the blog loads extremely
    fast for me on Safari. Excellent Blog!

    Reply
  • December 13, 2014 at 11:12 am
    Permalink

    This has to be my second favourite commentary of the last few
    days, i can’t tell you number one, it may offend you!

    Reply
    • December 13, 2014 at 5:24 pm
      Permalink

      I am more than happy to know that you are getting benefited from my work. 😀

      Reply
  • December 21, 2014 at 12:03 am
    Permalink

    I’ve a inquiry concerning the piece, where can i
    contact the writer?

    Reply
  • December 21, 2014 at 5:12 pm
    Permalink

    terrific usage of language within the writing, it really did help
    when i was surfing around

    Reply
  • December 30, 2014 at 1:37 am
    Permalink

    Excellent post, i did read it two times so sorry for this, i’ve passed it on to
    my mates, so with any luck they’ll like it as well.

    Reply
    • December 31, 2014 at 5:18 pm
      Permalink

      Thank you very much 🙂

      Reply
  • February 9, 2015 at 5:19 am
    Permalink

    Hi,
    Thanks for your great upload. But i want to share one thing. I am using contact form 7 parallelly on my theme with this ajax registration. I have an issue with CF7 form, it doesn’t returns validations and success message. It loads the ajax and leaves as it is. Is there any solution for this?

    Reply
    • February 9, 2015 at 6:12 am
      Permalink

      This tutorial is not using CF7 for registration. Rather than using CF7 you can build your custom registration form.

      Reply
  • February 10, 2015 at 12:15 am
    Permalink

    Hello,

    Trying to get our developer to add a customized message after a user registers on our website. (Thank you for registering with us ……… you will find an email from us, please confirm your email. You may also unsubscribe by clicking this link

    1)My question is shouldn’t that come with wordpress template already, in the cpanel some where?

    My developers translation
    2)To do: Email customization for new user registration, forgot password and email verification before account is activated. Whenever a candidate posts a resume, or an employer posts a job, an account is automatically created for them.
    There is also the need for server configuration in order to prevent emails from going to users’ junk mail

    3)Which widget can we use that is inexpensive but quality for question #2

    Reply
  • May 19, 2015 at 7:02 pm
    Permalink

    Hola! Gracias porr esta información. Llevaba un rato buscando por internet sobre
    este tema hasta el momento en que he encontrado tu página.

    Está realmente biien el artículo. Sigue de esta forma!

    Reply
  • August 17, 2015 at 4:15 pm
    Permalink

    Hi,
    Thanks for the nice article , But i want a little bit different .
    After user created , i want to send an email verification , email to user and till user not verified .
    He will not able to login .

    How i can achieve this .Please help me out.

    Thank You

    Reply
  • August 31, 2015 at 8:25 pm
    Permalink

    Sending 2 ajax request for one time

    Reply
  • January 7, 2016 at 8:46 am
    Permalink

    can any one suggest me where shoe registration detail

    Reply
  • February 5, 2016 at 10:55 am
    Permalink

    This is grate code for custom registration. I want to custom login so please provide custom login code.
    Thanks

    Reply
  • March 2, 2016 at 3:56 pm
    Permalink

    Hi!

    Excellent post! I added some ACF fields, but I’m not able to save the data with update_user_meta. Do you have any idea why?

    Reply
  • August 17, 2017 at 12:23 pm
    Permalink

    i’m totally new for wordpress and i don’t know where to write this code.
    can you please give me any suggestion

    Reply
    • Ankit
      August 18, 2017 at 6:48 am
      Permalink

      This code can be added to bottom of functions.php file in active theme directory.

      Reply

Leave a Reply

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