How to register user in wordpress

WordPress provides wp_insert_user and wp_create_user to create users.For this I am going to create shortcode for Register Form and custom hook to process form submission.

Register Form Shortcode

add_shortcode() function in wordpress provides the way to create shortcode and use in wordpress page using editor.Shortcode should be included in [shortcode] in wordpres page.You can define this code to functions.php or plugin file.

 
<?php 
add_shortcode('register_form','register_form'); 
function register_form(){ include_once "register.php"; }
 ?>

register.php


<form action="" method="post">
<table>
<tr>
<td>User Name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" name="firstname"></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lastname"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>City</td>
<td><input type="text" name="city"></td>
</tr>
<tr>
<td>Address</td>
<td><textarea name="address"></textarea></td>
</tr>
</table>
</form>

Form Submission

Here I’m going to define a custom hook for form submission.wp_create_user() function used to create a new user and add_user_meta() function to add meta information about user.Here first username and email check is done before user register.

<?php 
$user_name = $_POST['username']; 
$user_email = $_POST['email'];
 $password = $_POST['password']; 
$firstname = $_POST['firstname']; 
$lastname = $_POST['lastname']; 
$city = $_POST['city'];
 $address = $_POST['address'];
 $user_id = username_exists( $user_name );
 if ( !$user_id and email_exists($user_email) == false ) {
 $user_id = wp_create_user( $user_name, $password, $user_email );
 add_user_meta($user_id,"first_name",$firstname); 
add_user_meta($user_id,"last_name",$lastname); 
add_user_meta($user_id,"city",$city); 
add_user_meta($user_id,"address",$address); 
$subject = "Registration"; 
$message = "Dear User,Thanks for registration."; 
add_filter( 'wp_mail_content_type', 'set_html_content_type' ); 
wp_mail($user_email,$subject, $message ); } 
?> 

Leave a Reply