Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

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 );
share|improve this answer
    
Thanks @Bainternet, I have written the script. As you said yeah we need to include registration.php –  Kathir Maya May 12 '11 at 9:20
    
thanks a lot @bainternet ;) –  Sagive SEO Jul 18 '12 at 11:38
1  
Including registration.php is no longer needed from 3.1 –  Omar Abid Jul 30 '13 at 11:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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