How to send email password when creating a new user by API in Wordpress?

It is possible to create a new user by API with the following line:

$user_id = wp_insert_user( $user_data );

I wonder how to send the newly created user an email that contains his password? Is there any function in Wordpress API that handles this job or should I create and send an email by myself?

Answers


I assume you are generating the password and adding it to the $user_data array?

If not, you can use this to generate a password -

$this->password = wp_generate_password(6, false);
$user_data['user_pass'] = $this->password;

And while there probably is a way of hooking in to the generic WP send password email, I just use my own. That way, I can customise the content, and make it look like other emails from my site.

Note that I have set up a Class for registration, so if you have not, you will need to remove instances of $this->.

function prepare_email(){

        $confirmation_to = $_REQUEST['email_address'];
        $confirmation_subject = 'Confirmation - Registration to My Site';
        $confirmation_message = 'Hi '.$_REQUEST['first_name'].',<br /></br />Thank you for registering with My Site. Your account has been set up and you can log in using the following details -<br /><br />'
            .'<strong>Username:</strong> '.$_REQUEST['username']
            .'<br /><strong>Password:</strong> '.$this->password
            .'<br /><br />Once you have logged in, please ensure that you visit the Site Admin and change you password so that you don\'t forget it in the future.';
        $headers = 'MIME-Version: 1.0'."\r\n";
        $headers.= 'Content-type: text/html; charset=iso-8859-1'."\r\n";
        $confirmation_headers = $headers.'From: My Site <no-reply@mysite.com>'."\r\n";

        $this->form_for_email = compact('confirmation_to', 'confirmation_subject', 'confirmation_message', 'confirmation_headers');

    }

As David guessed (but didn't specify), there is some functionality inside Wordpress to do this: wp_new_user_notification($user_id, $user_pass).

So, rewriting the above code, it should look like this (code has been edited after parameter deprecation in 4.3.1):

$user_id = wp_insert_user( $user_data );
wp_new_user_notification( $user_id, null, 'both' );

Edit: Please also see @ale's comment below.


Need Your Help

Deleting all the rows in a JTable

java swing jtable

I need to remove all the rows in my JTable.

Origin of "Mon Jan 2 15:04:05 MST 2006" in golang

time go

In golang documentation, it is stated that :