J'ai un modèle personnalisé pour l'enregistrement de l'utilisateur. Je veux utiliser une fonction pour insérer des utilisateurs. Puis-je appeler directement la fonction wp_insert_user ()?
Oui, vous pouvez, mais vous devez inclure registration.php
pour la validation, par exemple:
//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 );