Warning: Undefined array key "show" in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 13
Warning: Undefined variable $bodyClass in /home/shtechno/public_html/shivamkhare.in/wp-content/themes/shivam/header.php on line 50
class="post-template-default single single-post postid-233 single-format-standard vertical">

WordPress custom register code & update ACF field

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).

WordPress Redirection

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/');
} }

Create custom field to users with ACF Plugin.

For creating a custom field go to the Custom Field Menu on left and create a new Group, see Screenshot for instruction.

Create register form

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 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 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 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 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-->
        <?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-->

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

    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})(]?)$/;

        $('#error_usernm').html('Please enter username.').css('visibility', 'visible');
        errCnt += 1;
    if(email == ""){
        $('#error_email').html('Please enter Email Id.').css('visibility', 'visible');
        errCnt += 1;
    }else if((!emailRegEx.test(email))){
        $('#error_email').html('Please enter valid Email Id.').css('visibility', 'visible');
        errCnt += 1;
    if(mobile_no == '') {
        $('#error_mobile_no').html('Please enter mobile number').css('visibility', 'visible');
        errCnt += 1;
    if(city == '') {
        $('#error_city').html('Please enter your city').css('visibility', 'visible');
        errCnt += 1;
        $('#error_password').html('Please enter password.').css('visibility', 'visible');
        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) {
           var error = response.split('+');
           if(error[0] == 'success'){
               window.location.href = window.location.origin + '/dashboard/';
                $('#formerror').html(error[0]).css('visibility', 'visible');
           }, 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);
        $errors[] = 'This email is already registered.<br>';
    if(empty($sanitize_user_username) || !validate_username($user_username)) 
        $errors[] = 'Invalid user name.<br>';
        $errors[] = 'User name already exists.<br>';
		$user_id = wp_create_user($sanitize_user_username, $user_pass, $user_email);
            $errors[] = 'Registration failed';
            $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";
        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.