Custom User Registration/Signup Using AJAX – WordPress
Few years’ back I’ve made a tutorial on how to create Custom User Registration/Signup in WordPress using pure PHP, it’s a straight forward tutorial or we can say it’s simply enough for medium and beginner, I have to accept it’s outdated pretty much outdated nowadays, so I decided to enhance it a bit by using WP AJAX, WP has a bunch of features included so why not use it?
We still gonna use same WordPress method for saving user to database the only different is we use jQuery and WP AJAX to save and get returned data, no browser loading and with a preloading effect it’s pretty cool.
Let’s get started
HTML Code
This is just a normal HTML code and form for user to input username and password, yeah we ask only username and password but if you’d like to add more like first name and last name, of course it’s possible but for the sake of this tutorial I just use two input fields, (hope you don’t get mad).
<div class="userRegistration textCenter">
<!--message wrapper-->
<div id="message" class="alert-box"></div>
<h2>HELLO,</h2>
<p>Don't have an account yet? Create one now.</p>
<form method="post" id="rsUserRegistration">
<?php
// to make our script safe, it's a best practice to use nonce on our form to check things out
if ( function_exists( 'wp_nonce_field' ) )
wp_nonce_field( 'rs_user_registration_action', 'rs_user_registration_nonce' );
?>
<p><input type="text" name="log" id="log" placeholder="Username" /></p>
<p><input type="password" name="pwd" id="pwd" placeholder="Password" /></p>
<p>
<input type="submit" id="submit" class="button btn-outline" value="Join" />
<!--make sure you have ajax-loader.gif image added into your theme images directory-->
<img src="<?php echo get_stylesheet_directory_uri(); ?/>/images/ajax-loader.gif" id="preloader" alt="Preloader" />
</p>
</form>
</div>
JS Code
Location and filename: THEME_DIRECTORY/js/theme-ajax.js
This code send and display returned data in PHP code below
jQuery(document).ready(function($) {
// for user registration form
$("form#rsUserRegistration").submit(function(){
var submit = $(".userRegistration #submit"),
preloader = $(".userRegistration #preloader"),
message = $(".userRegistration #message"),
contents = {
action: 'user_registration',
nonce: this.rs_user_registration_nonce.value,
log: this.log.value,
pwd: this.pwd.value,
};
// disable button onsubmit to avoid double submision
submit.attr("disabled", "disabled").addClass('disabled');
// Display our pre-loading
preloader.css({'visibility':'visible'});
$.post( theme_ajax.url, contents, function( data ){
submit.removeAttr("disabled").removeClass('disabled');
// hide pre-loader
preloader.css({'visibility':'hidden'});
// check response data
if( 1 == data ) {
// redirect to home page
window.location = theme_ajax.site_url;
} else {
// display return data
message.html( data );
}
});
return false;
});
});
PHP Code
You can paste this code into your current theme’s functions.php
file or create another file if you prefer.
This code checks on submitted username and password fields and if everything is clear then it’s ready to save the user to database.
More info on wp_ajax and wp_ajax_nopriv can be found here.
add_action( 'wp_ajax_nopriv_user_registration', 'rs_user_registration_callback' );
add_action( 'wp_ajax_user_registration', 'rs_user_registration_callback' );
/*
* @desc Register user
*/
function rs_user_registration_callback() {
global $wpdb;
$error = '';
$success = '';
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'rs_user_registration_action' ) )
die ( '<p class="error">Security checked!, Cheatn huh?</p>' );
$log = $_POST['log'];
$pwd = $_POST['pwd'];
if( empty( $log ) ) {
$error = 'Username field is required.';
} else if( empty( $pwd ) ) {
$error = 'Password field is required.';
} else {
$user_params = array (
'user_login' => apply_filters( 'pre_user_user_login', $log ),
'user_pass' => apply_filters( 'pre_user_user_pass', $pwd ),
'role' => 'subscriber'
);
$user_id = wp_insert_user( $user_params );
if( is_wp_error( $user_id ) ) {
$error = $user_id->get_error_message();
} else {
do_action( 'user_register', $user_id );
$success = 1;
}
}
if( ! empty( $error ) )
echo '<p class="error">'. $error .'</p>';
if( ! empty( $success ) )
echo $success;
// return proper result
die();
}
Workaround
By default wp_ajax didn’t work in front-end or submitting data to admin-ajax.php
file in front-end directly, luckily WordPress has wp_localize_script()
function we can use, this function localizes a registered script with data for a JavaScript variable.
Paste the below code into your functions.php
file, to avoid any conflict I suggest add it in init action
// localize wp-ajax, notice the path to our theme-ajax.js file
wp_enqueue_script( 'rsclean-request-script', get_stylesheet_directory_uri() . '/js/theme-ajax.js', array( 'jquery' ) );
wp_localize_script( 'rsclean-request-script', 'theme_ajax', array(
'url' => admin_url( 'admin-ajax.php' ),
'site_url' => get_bloginfo('url'),
'theme_url' => get_bloginfo('template_directory')
) );
Hope that helps, Happy coding ^_^