Custom function for user register in wp?

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?

Related posts

Leave a Reply

2 comments

  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 );