In this blog, you’ll learn how to create WordPress register form with custom code through AJAX also add value to custom register fields (Advanced Custom Fields).
Firstly we have to create page redirection for if you are already logged in so auto redirect to dashboard page or if you not logged in user so automatic redirect to Login page.
Following code you have to paste in your function.php or paste the top of the header.php (see screenshot of header.php)
Copy the code from here:
<?php if(is_page_template(array('template-login.php', 'template-register.php', 'template-lostpwd.php'))){ if(is_user_logged_in()){ wp_redirect ('/dashboard/'); } }else{ if(!is_user_logged_in()){ wp_redirect ('/login/');
} }
?>
For creating a custom field go to the Custom Field Menu on left and create a new Group, see Screenshot for instruction.
Code for register page or template-register.php.
Here the code for register form with Nonces.
<div class="register-block">
<h1>Member register</h1>
<form method="post" action="/submit_register/" id="registerform" enctype="multipart/form-data" >
<div class="field-group mb-3">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" />
<label id="error_usernm" class="error"></label> <!-- show error -->
</div>
<div class="field-group mb-3">
<label for="email">Email</label>
<input type="email" name="email" id="email" class="form-control" />
<label id="error_email" class="error"></label> <!--show error-->
</div>
<div class="field-group mb-3">
<label for="mobile_no">Mobile No</label>
<input type="text" name="mobile_no" id="mobile_no" class="form-control" />
<label id="error_mobile_no" class="error"></label> <!--show error-->
</div>
<div class="field-group mb-3">
<label for="city">City</label>
<input type="text" name="city" id="city" class="form-control" />
<label id="error_city" class="error"></label> <!--show error-->
</div>
<div class="field-group mb-3">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" autocomplete="off" />
<label id="error_password" class="error"></label> <!--show error-->
</div>
<?php wp_nonce_field( 'submit_register' ); //"submit_login" same as action url ?>
<input type="submit" class="registersubmit" value="Register" />
<div id="formerror" ></div> <!-- Display result here-->
</form>
</div>
On the front end, suppose we wanted to add a nonce to a form submission. We’ll do this with the wp_nonce_field convenience function:
Form validation and Submit
Click on the submit button firstly we have to check the input field valid or not with jQuery validation (Username or Password are protracted) then process to login check.
Copy the code for custom.js or footer.php
$(document).on('click','.registersubmit',function(e){
e.preventDefault();
var username = $.trim($('#username').val());
var email = $.trim($('#email').val());
var mobile_no = $.trim($('#mobile_no').val());
var city = $.trim($('#city').val());
var password = $.trim($('#password').val());
var errCnt = 0;
var emailRegEx=/^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$/;
if(username==""){
$('#error_usernm').html('Please enter username.').css('visibility', 'visible');
$('#error_usernm').show();
errCnt += 1;
}
if(email == ""){
$('#error_email').html('Please enter Email Id.').css('visibility', 'visible');
$('#error_email').show();
errCnt += 1;
}else if((!emailRegEx.test(email))){
$('#error_email').html('Please enter valid Email Id.').css('visibility', 'visible');
$('#error_email').show();
errCnt += 1;
}
if(mobile_no == '') {
$('#error_mobile_no').html('Please enter mobile number').css('visibility', 'visible');
$('#error_mobile_no').show();
errCnt += 1;
}
if(city == '') {
$('#error_city').html('Please enter your city').css('visibility', 'visible');
$('#error_city').show();
errCnt += 1;
}
if(password==""){
$('#error_password').html('Please enter password.').css('visibility', 'visible');
$('#error_password').show();
errCnt += 1;
}
var formData=$('#registerform').serialize();
var data = formData+'&action=register_form';
var ajaxurl = '/wp-admin/admin-ajax.php';
if(errCnt == 0){
$.post(ajaxurl, data, function(response) {
console.log(response);
var error = response.split('+');
if(error[0] == 'success'){
window.location.href = window.location.origin + '/dashboard/';
}else{
$('#formerror').html(error[0]).css('visibility', 'visible');
}
setTimeout(function(){
$('#formerror').html('');
}, 4000);
});
}
});
Check User or go to login
Copy the code for function.php
add_action( 'wp_ajax_register_form', 'register_form' );
add_action( 'wp_ajax_nopriv_register_form', 'register_form' );
function register_form(){
global $wpdb;
$nonce = $_REQUEST['_wpnonce'];
$errors = array();
if ( ! wp_verify_nonce( $nonce, 'submit_register' ) ) {
exit; // Get out of here, the nonce is rotten!
}
$errors = array();
$user_username = esc_attr($_POST['username']);
$user_email = esc_attr($_POST['email']);
$user_mobile = esc_attr($_POST['mobile_no']);
$user_city = esc_attr($_POST['city']);
$user_pass = esc_attr($_POST['password']);
$sanitize_user_username = sanitize_user($user_username);
$user_email = apply_filters('user_registration_email', $user_email);
if(email_exists($user_email))
$errors[] = 'This email is already registered.<br>';
if(empty($sanitize_user_username) || !validate_username($user_username))
$errors[] = 'Invalid user name.<br>';
elseif(username_exists($sanitize_user_username))
$errors[] = 'User name already exists.<br>';
if(empty($errors)){
$user_id = wp_create_user($sanitize_user_username, $user_pass, $user_email);
if(!$user_id){
$errors[] = 'Registration failed';
}else{
$user = new WP_User( $user_id );
$user->set_role( 'contributor' ); // Set User Role
update_user_option($user_id, 'default_password_nag', true, true);
wp_new_user_notification($user_id, $user_pass);
update_user_meta ($user_id, 'mobile_no', $user_mobile);
update_user_meta( $user_id, 'city', $user_city );
do_action ('user_register', $user_id);
$user_data = get_userdata ($user_id);
if ($user_data !== false) {
echo $error = "success";
}
}
}else{
foreach($errors as $result) {
echo $result . '';
}
}
}
The nonce is unknown to the hacker, he can’t craft a fake link that will do harm. Any malicious attempts will be squashed at the wp_verify_nonce check. We’ve stopped the hacker, right?! For many cases, yes. We’ve made it much more difficult for a hacker to forge a request.