How to add a WordPress Registration Form to a page

How to display a WordPress registration form on any page using a custom shortcode, enhancing the wordpress registration page to submit the form via ajax, offer users a richer wordpress registration experience.

Enabling user registration in WordPress

Settings to enable user registration in wordpress can be found via Settings > General page in the WordPress admin area, scroll down to the checkbox labelled “Membership – Anyone can register”, once done make sure you set the field labelled “New user default role” to the correct role to give new registered users.

With user registration enabled in WordPress, users will received an email message when they register an account, you can customise the wordpress registration email to provide users with relevent information relating to their account.

Create a WordPress registration from shortcode

Displaying a wordpress registration form on the front end of our website can be done using the Shortcode API to register our user register form shortcode using add_shortcode, we will copy the main structure of our registration form from the core wordpress user registration form, the main reason for this is to allow the registration form to be easily be extended.

function jcul_register_form_shortcode($atts)
{

    if (!get_option('users_can_register')) {
        return '<p>Registration is disabled</p>';
    }

    $user_login = '';
    $user_email = '';

    /**
     * Filters the registration redirect URL.
     *
     * @since 3.0.0
     *
     * @param string $registration_redirect The redirect destination URL.
     */
    $redirect_to = apply_filters('registration_redirect', '');

    ob_start();
?>
    <form name="registerform" id="registerform" action="<?php echo esc_url(site_url('wp-login.php?action=register', 'login_post')); ?>" method="post" novalidate="novalidate">

        <div class="jcul-ajax-error-message"></div>

        <p>
            <label for="user_login"><?php _e('Username'); ?></label>
            <input type="text" name="user_login" id="user_login" class="input" value="<?php echo esc_attr(wp_unslash($user_login)); ?>" size="20" autocapitalize="off" />
        </p>
        <p>
            <label for="user_email"><?php _e('Email'); ?></label>
            <input type="email" name="user_email" id="user_email" class="input" value="<?php echo esc_attr(wp_unslash($user_email)); ?>" size="25" />
        </p>
        <?php

        /**
         * Fires following the 'Email' field in the user registration form.
         *
         * @since 2.1.0
         */
        do_action('register_form');

        ?>
        <p id="reg_passmail">
            <?php _e('Registration confirmation will be emailed to you.'); ?>
        </p>
        <br class="clear" />
        <input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />
        <input type="hidden" name="jcul-ajax-enabled" value="1" />
        <p class="submit">
            <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Register'); ?>" />
        </p>
    </form>
<?php
    return ob_get_clean();
}

add_shortcode('register_form', 'jcul_register_form_shortcode');

Adding the registration form to a page

Displaying the registration form on any page can be added by pasting the shortcode into the classic editor WYSIWYG, or by adding a shortcode block into the gutenberg editor and pasting it there.

[register_form]

Adding the wordpress registration form to any other part of the website can be achieved by using the do_shortcode function in php.

do_shortcode('[register_form]');

Submit user registration form via AJAX

Adding AJAX to the wordpress registration form stops the user being sent to wp-login.php when the form is submitted, instead they will remain on the current page while the form is submitted and it will display any errors as they happen, providing the user with better user experience.

Using the jquery library we capture the user registration forms submission via the submit event, preventing its default submission and instead send it using jQuerys $.ajax method, displaying the response inline at the top of the form.

The button_text function stops the user submitting the registration form multiple time, by disabling the submit button and changing its text to alert the user while the form is processing.

(function($){

var button_text = function(el, text = 'Loading') {

  if (!el.data('text')) {
    el.data('text', el.val());
  }

  if (!text) {
    el.prop('disabled', false);
    el.val(el.data('text'));
  } else {
    el.prop('disabled', true);
    el.val(text);
  }
}

$('body').on('submit', '#registerform', function (e) {
  var $form = $(this);
  e.preventDefault();

  button_text($form.find('input[type="submit"]'));

  $.ajax({
    url: $form.attr('action'),
    type: 'POST',
    dataType: 'json',
    data: $form.serialize(),
    success: function (response) {
      if (response.status !== 'S') {
        $form
          .find('.jcul-ajax-error-message')
          .html('<p>An unknown error occured</p>');
        return;
      }

      if (response.data.register_user !== 1) {
        $form
          .find('.jcul-ajax-error-message')
          .html('<p>' + response.data.errors.join('<br />') + '</p>');
        return;
      }

      $form
        .find('.jcul-ajax-error-message')
        .html('<p>User account has been registered.</p>');
    },
    complete: function () {
      button_text($form.find('input[type="submit"]'), false);
    },
  });
});

})(jQuery);

Capture wordpress registration form errors as a AJAX response

The wordpress registration_errors filter allows us to capture errors that have happened during the user registration process, we check to see if the request has the jcul-ajax-enabled flag set, if so we intercept the request checking for any errors then we output our json data displaying a list of errors and setting the register_user flag to 0, to report the failed user registration.

function jcul_register_json_error_response($errors){

    if (isset($_POST['jcul-ajax-enabled']) && $errors->has_errors()) {
        echo wp_json_encode([
            'status' => 'S',
            'data' => [
                'register_user' => 0,
                'errors' => $errors->get_error_messages()
            ]
        ]);
        exit;
    }

    return $errors;
}

add_filter('registration_errors', 'jcul_register_json_error_response', PHP_INT_MAX);

Capture successful registration as a AJAX response

we can use the register_new_user hook to capture a successful user registration submission, checking that the jcul-ajax-enabled flag has been set, and if so returning a json response witht the register_user flag set to 1, letting the form know that the user registration was complete.

function jcul_register_json_success_response($user_id){

    if (!isset($_POST['jcul-ajax-enabled'])) {
        return;
    }
    echo wp_json_encode([
        'status' => 'S',
        'data' => [
            'register_user' => 1,
        ]
    ]);
    exit;
}

add_action('register_new_user', 'jcul_register_json_success_response');

Conclusion

In this article we covered how to create a wordpress registration page using a custom shortcode and display it using gutenberg or the classic editor, also how to capture and return a registration submission as a JSON response which updates the wordpress registration form accordingly.

Leave a Reply

Fields marked with an * are required to post a comment