如何在Wordpress中通过API创建新用户时发送电子邮件密码?

Mer*_*glu 4 api wordpress

可以通过API使用以下行创建新用户:

$user_id = wp_insert_user( $user_data );
Run Code Online (Sandbox Code Playgroud)

我想知道如何向新创建的用户发送包含其密码的电子邮件?Wordpress API中是否有任何功能可以处理这项工作,还是应该由我自己创建和发送电子邮件?

Chr*_*ian 26

正如David所猜测的那样(但没有指明),Wordpress中有一些功能可以做到这一点:wp_new_user_notification($user_id, $user_pass).

因此,重写上面的代码,它应该是这样的(代码已在4.3.1中的参数弃用后编辑):

$user_id = wp_insert_user( $user_data );
wp_new_user_notification( $user_id, null, 'both' );
Run Code Online (Sandbox Code Playgroud)

编辑:请参阅下面的@ ale的评论.

  • 自4.3.1起.不推荐使用此函数的第二个参数.现在你应该传递'null'作为一个值.因此密码不应作为参数传递给此函数.作为第三个参数,我们有'$ notify'选项可以接受:admin,user,both.此参数指定应向谁发送通知电子邮件. (3认同)

Dav*_*ard 7

我假设您正在生成密码并将其添加到$user_data阵列?

如果没有,您可以使用它来生成密码 -

$this->password = wp_generate_password(6, false);
$user_data['user_pass'] = $this->password;
Run Code Online (Sandbox Code Playgroud)

虽然可能有一种方法可以挂钩通用WP发送密码电子邮件,但我只是使用自己的.这样,我可以自定义内容,使其看起来像我网站上的其他电子邮件.

请注意,我已经设置了一个用于注册的类,因此如果还没有,则需要删除实例$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');

    }
Run Code Online (Sandbox Code Playgroud)