Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Custom login and registration forms

I use this function as a plugin but you can use it also in function.php.

But i still didn’t found a way to add the user role I used it like a textbox but also we can use it in select but I don’t know if it works correctly I hope someone can add it if it’s not correct.

<?php

/*
  Plugin Name: Registration Form
  Description: Custom sign up form.
  Version: 1.1
  Author: Me
 */



/////////////////
// PLUGIN CORE //
/////////////////

function cr(&$fields, &$errors) {

  // Check args and replace if necessary
  if (!is_array($fields))     $fields = array();
  if (!is_wp_error($errors))  $errors = new WP_Error;

  // Check for form submit
  if (isset($_POST['submit'])) {

    // Get fields from submitted form
    $fields = cr_get_fields();

    // Validate fields and produce errors
    if (cr_validate($fields, $errors)) {

      // If successful, register user
      wp_insert_user($fields);

      // And display a message
      echo 'Registration complete. Goto <a href="' . get_site_url() . '/wp-login.php">login page</a>.';

      // Clear field data
      $fields = array(); 
    }
  }

  // Santitize fields
  cr_sanitize($fields);

  // Generate form
  cr_display_form($fields, $errors);
}

function cr_sanitize(&$fields) {
  $fields['user_login']   =  isset($fields['user_login'])  ? sanitize_user($fields['user_login']) : '';
  $fields['user_pass']    =  isset($fields['user_pass'])   ? esc_attr($fields['user_pass']) : '';
  $fields['user_email']   =  isset($fields['user_email'])  ? sanitize_email($fields['user_email']) : '';
  $fields['user_url']     =  isset($fields['user_url'])    ? esc_url($fields['user_url']) : '';
  $fields['first_name']   =  isset($fields['first_name'])  ? sanitize_text_field($fields['first_name']) : '';
  $fields['last_name']    =  isset($fields['last_name'])   ? sanitize_text_field($fields['last_name']) : '';
  $fields['nickname']     =  isset($fields['nickname'])    ? sanitize_text_field($fields['nickname']) : '';
  $fields['description']  =  isset($fields['description']) ? esc_textarea($fields['description']) : '';
  $fields['role']  =  isset($fields['role']) ? esc_textarea($fields['role']) : '';
}

function cr_display_form($fields = array(), $errors = null) {

  // Check for wp error obj and see if it has any errors  
  if (is_wp_error($errors) && count($errors->get_error_messages()) > 0) {

    // Display errors
    ?><ul><?php
    foreach ($errors->get_error_messages() as $key => $val) {
      ?><li>
        <?php echo $val; ?>
      </li><?php
    }
    ?></ul><?php
  }

  // Disaply form

  ?><form action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
    <div>
      <label for="user_login">Username <strong>*</strong></label>
      <input type="text" name="user_login" value="<?php echo (isset($fields['user_login']) ? $fields['user_login'] : '') ?>">
    </div>

    <div>
      <label for="user_pass">Password <strong>*</strong></label>
      <input type="password" name="user_pass">
    </div>

    <div>
      <label for="email">Email <strong>*</strong></label>
      <input type="text" name="user_email" value="<?php echo (isset($fields['user_email']) ? $fields['user_email'] : '') ?>">
    </div>

    <div>
      <label for="website">Website</label>
      <input type="text" name="user_url" value="<?php echo (isset($fields['user_url']) ? $fields['user_url'] : '') ?>">
    </div>

    <div>
      <label for="firstname">First Name</label>
      <input type="text" name="first_name" value="<?php echo (isset($fields['first_name']) ? $fields['first_name'] : '') ?>">
    </div>

    <div>
      <label for="website">Last Name</label>
      <input type="text" name="last_name" value="<?php echo (isset($fields['last_name']) ? $fields['last_name'] : '') ?>">
    </div>

    <div>
      <label for="role">Role : Author, Contributor, Editor and Subscriber</label>
      <input type="text" name="role" value="<?php echo (isset($fields['role']) ? $fields['role'] : '') ?>">
    </div>

    <div>
      <label for="nickname">Nickname</label>
      <input type="text" name="nickname" value="<?php echo (isset($fields['nickname']) ? $fields['nickname'] : '') ?>">
    </div>

    <div>
      <label for="bio">About / Bio</label>
      <textarea name="description"><?php echo (isset($fields['description']) ? $fields['description'] : '') ?></textarea>
    </div>

    <input type="submit" name="submit" value="Register">
    </form><?php
}

function cr_get_fields() {
  return array(
    'user_login'   =>  isset($_POST['user_login'])   ?  $_POST['user_login']   :  '',
    'user_pass'    =>  isset($_POST['user_pass'])    ?  $_POST['user_pass']    :  '',
    'user_email'   =>  isset($_POST['user_email'])   ?  $_POST['user_email']        :  '',
    'user_url'     =>  isset($_POST['user_url'])     ?  $_POST['user_url']     :  '',
    'first_name'   =>  isset($_POST['first_name'])   ?  $_POST['first_name']        :  '',
    'last_name'    =>  isset($_POST['last_name'])    ?  $_POST['last_name']        :  '',
    'nickname'     =>  isset($_POST['nickname'])     ?  $_POST['nickname']     :  '',
    'description'  =>  isset($_POST['description'])  ?  $_POST['description']  :  '',
    'role'  =>  isset($_POST['role'])  ?  $_POST['role']  :  ''
  );
}

function cr_validate(&$fields, &$errors) {

  // Make sure there is a proper wp error obj
  // If not, make one
  if (!is_wp_error($errors))  $errors = new WP_Error;

  // Validate form data

  if (empty($fields['user_login']) || empty($fields['user_pass']) || empty($fields['user_email'])) {
    $errors->add('field', 'Required form field is missing');
  }

  if (strlen($fields['user_login']) < 4) {
    $errors->add('username_length', 'Username too short. At least 4 characters is required');
  }

  if (username_exists($fields['user_login']))
    $errors->add('user_name', 'Sorry, that username already exists!');

  if (!validate_username($fields['user_login'])) {
    $errors->add('username_invalid', 'Sorry, the username you entered is not valid');
  }

  if (strlen($fields['user_pass']) < 5) {
    $errors->add('user_pass', 'Password length must be greater than 5');
  }

  if (!is_email($fields['user_email'])) {
    $errors->add('email_invalid', 'Email is not valid');
  }

  if (email_exists($fields['user_email'])) {
    $errors->add('email', 'Email Already in use');
  }

  if (!empty($fields['user_url'])) {
    if (!filter_var($fields['user_url'], FILTER_VALIDATE_URL)) {
      $errors->add('user_url', 'Website is not a valid URL');
    }
  }

  // If errors were produced, fail
  if (count($errors->get_error_messages()) > 0) {
    return false;
  }

  // Else, success!
  return true;


}



///////////////
// SHORTCODE //
///////////////

// The callback function for the [cr] shortcode
function cr_cb() {
  $fields = array();
  $errors = new WP_Error();

  // Buffer output
  ob_start();

  // Custom registration, go!
  cr($fields, $errors);

  // Return buffer
  return ob_get_clean();
}
add_shortcode('cr', 'cr_cb');

Related Posts:

  1. How to modify the action attribute of the wp-login.php?action=register form?
  2. How Can I Move Data From Form 1 To Form 2
  3. How to change the login page without a plugin and not only customizing logo and text around the form?
  4. Custom user fields validation on registration
  5. add unique code required to register
  6. Redirect all pages to the custom login page except for the registration page
  7. Change the login button on the login page
  8. Custom ReCaptcha Login
  9. Creating my own Admin Forms in a WordPress CMS?
  10. What is the proper way to apply the login_form_bottom filter?
  11. How to override wp-login.php
  12. Remove Links from Login page
  13. generate unique number when registering a user
  14. setting a specific home page for logged in users
  15. Change “logged in” link in (you must be logged in to post a comment)
  16. Redirect to requested page after (custom) login
  17. Adding extra info via GET while registeration in wordpress
  18. Many users with strange names register, but don’t leave comments. Should I be afraid?
  19. Customizing the default logout page of WordPress
  20. Is there any good tutorial to write custom login, registration and password recovery forms? [closed]
  21. How do I remove the eye icon that shows visibility on login screen and reset password screen
  22. Change register form action url
  23. Using transients to store captchas
  24. Custom Login and Registration form in Ajax
  25. Last time a user logged in
  26. How to pass external variables to the wp_new_user_notification_email filter?
  27. How can I allow access to multiple users, using the same login, at the same time?
  28. How to implement a custom password field that redirects to another page upon correct password?
  29. Add Div to Comment Form
  30. WordPress custom login page
  31. Add custom user profile field to default WordPress MultiSite registration form
  32. What’s wrong with Customizing new user notification email by add_filter?
  33. Function to allow “Anyone can register”?
  34. Adding a login form that concatenates three fields into a username
  35. Properly customizing login/register form
  36. Adding custom field in all widgets, but at the top of the form, in admin area
  37. I want to submit multiple users if checkbox is checked
  38. How to add an extra variable to login and authenticate it?
  39. Custom search to display results within same page
  40. Login/Logout Session Sharing – Multiple WordPress Installations
  41. Auto login from custom registration form
  42. Custom login with external provider iframe and data object
  43. Diffrent User registration form for doctor and patient
  44. Deep customization of wp-login.php
  45. User can not login
  46. Lost password empty field error redirect to custom login
  47. Custom Log In Screen – Disable password recovery [duplicate]
  48. Multi-site User Sessions
  49. A truely custom login page?
  50. Add Field to WordPress Register Form
  51. easy steps to make front end form without plugin
  52. Switch between WordPress websites easy for an end user
  53. Lost password and back to blog in same line
  54. I w’d like to know If there are simple solutions to integrate other CMSs to wordpress
  55. Saving contact form 7 data into custom Table
  56. Woocommerce custom checkout form
  57. Restrict content access to logged in users
  58. WordPress registration page template
  59. Custom Form not generating URL
  60. Create Unique ID for user
  61. URL and Site title outputting on Login page
  62. Is it possible to integrate a custom login feature with wordpress?
  63. Custom Register Link on Backend Form
  64. Hook before user is created and make some custom validation
  65. How do I make Dynamic Student Admission Form?
  66. Linking form to user meta fields
  67. Removing “Failed” query argument upon successful login
  68. Validate user login in php
  69. How to create multipage form and redirect to specific URL based on inpput?
  70. No plugin populate user information in to form
  71. how to change the url rediction of the woocommerce login page of the flatsome theme for my own in wordpress?
  72. How do I add a dropdown menu to a form?
  73. How to change Login default blue admin color?
  74. Latest update broke my custom login CSS
  75. Trouble with custom login page
  76. Wrap WordPress Login Form in custom Div
  77. How to automatically pull an information from a form field onto an other page?
  78. How to submit form data in the same page in WordPress without reloading the page?
  79. Custom login doesn’t stay
  80. Check get_post value after wp-admin login
  81. Custom dropdown search form that allows users to select option B based from Option 1
  82. where can i find the login page in wordpress and add my header to it
  83. How to display all post from the same current usermeta
  84. Change the default WordPress image on the dashboard login to a custom image [duplicate]
  85. How to get name and email value from a custom form and add it to campaign monitor subscriber list?
  86. Pass the post ID
  87. Changing starting number of User ID
  88. Custom options – register, defaults and delete empty fields (Settings API)
  89. Two searchforms with different categories/posts per page
  90. Page template with custom html fields inside a content
  91. User registration add user ID?
  92. WordPress and Magento: let WordPress manage user registration and logins?
  93. Show Site Name on WP login screen
  94. how to manage Session in WordPress using custom login?
  95. How to get value from wp_usermeta table in database?
  96. How to stop login for SPECIFIC users BEFORE a specified date
  97. Must I rewrite the whole login form or can I jsut do a part
  98. Adding Custom Link anchors in the top menu that points to specific sections of the site home page
  99. Page with several user editable text content
  100. Is it possible to have one page with multiple items, or 2 blogs on a site?
Categories customization Tags customization, forms, login, user-registration
Image URL and size
Include HTML (Bootstrap Modal Box) with a plugin into my header

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress