2

I have a custom template for user registration. I want to use a function to insert users. Can I directly call wp_insert_user() function?

1 Answer 1

5

Yes you can but you need to include registration.php for validation something like:

//Need registration.php for data validation
require_once( ABSPATH . WPINC . '/registration.php');
$firstname = sanitize_text_field( $form_data['firstname'] );
$lastname = sanitize_text_field( $form_data['lastname'] );
$username = sanitize_text_field( $form_data['username'] );
$email = sanitize_text_field( $form_data['email'] );
//Add usernames we don't want used
$invalid_usernames = array( 'admin' );
//Do username validation
$username = sanitize_user( $username );
if ( !validate_username( $username ) || in_array( $username, $invalid_usernames ) ) {
    echo 'Username is invalid.';
}
if ( username_exists( $username ) ) {
    echo 'Username already exists.';
}
//Do e-mail address validation
if ( !is_email( $email ) ) {
    echo 'E-mail address is invalid.';
}
if (email_exists($email)) {
    echo 'E-mail address is already in use.';
}
//Everything has been validated, proceed with creating the user
//Create the user
$user_pass = wp_generate_password();
$user = array(
    'user_login' => $username,
    'user_pass' => $user_pass,
    'first_name' => $firstname,
    'last_name' => $lastname,
    'user_email' => $email
    );
$user_id = wp_insert_user( $user );

/*Send e-mail to admin and new user - 
You could create your own e-mail instead of using this function*/
wp_new_user_notification( $user_id, $user_pass );
2
  • Thanks @Bainternet, I have written the script. As you said yeah we need to include registration.php
    – Kathir
    May 12, 2011 at 9:20
  • 1
    Including registration.php is no longer needed from 3.1
    – Omar Abid
    Jul 30, 2013 at 11:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.