programing

워드프레스에서 API로 새로운 사용자를 생성할 때 이메일 비밀번호를 보내는 방법은?

easyjava 2023. 10. 1. 23:06
반응형

워드프레스에서 API로 새로운 사용자를 생성할 때 이메일 비밀번호를 보내는 방법은?

다음 행을 사용하여 API를 통해 새 사용자를 생성할 수 있습니다.

$user_id = wp_insert_user( $user_data );

새로 생성된 사용자에게 비밀번호가 포함된 이메일을 보내는 방법이 궁금합니다.워드프레스 API에 이 작업을 처리하는 기능이 있나요, 아니면 제가 직접 작성해서 메일을 보내야 하나요?

David이 추측했던 것처럼(구체적으로 언급하지는 않았지만), 워드프레스 내부에는 이를 수행할 수 있는 몇 가지 기능이 있습니다: .

따라서 위의 코드를 다시 작성하면 다음과 같이 보여야 합니다(코드는 4.3.1에서 매개 변수가 감소한 후 편집되었습니다).

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

편집 : 아래 @ale님의 코멘트도 참고해주세요.

암호를 생성하여 암호에 추가하는 것으로 가정합니다.$user_data배열?

그렇지 않은 경우 이를 사용하여 암호를 생성할 수 있습니다.

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

그리고 아마도 일반적인 WP send password e-메일을 연결하는 방법이 있겠지만, 저는 그냥 제 것을 사용합니다.그래야 콘텐츠를 사용자 정의할 수 있고, 내 사이트에서 보낸 다른 이메일처럼 보이게 할 수 있습니다.

등록을 위해 클래스를 설정했으므로 등록하지 않은 경우 다음의 인스턴스를 제거해야 합니다.$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');

    }

승인된 답변은 이제 더 이상 쓸모가 없습니다.를 이용한 답.wp_new_user_notification()작동하며 WordPress와 같은 메일을 보낼 것입니다.

그래도 David Gard가 제안한 대로 직접 메일을 보내길 원할 수도 있습니다.여기에 이것을 수행하는 코드가 있습니다.함수로 사용할 수도 있고, 수업에서 메소드로 사용할 수도 있습니다.

/**
 * Send mail with a reset password link
 *
 * @param  int $user_id  User ID
 */
function notify_new_user( $user_id )
{
    $user = get_userdata( $user_id );

    $subject   = '[website] Connection details';
    $mail_from = get_bloginfo('admin_email');
    $mail_to   = $user->user_email;
    $headers   = array(
        'Content-Type: text/html; charset=UTF-8',
        'From: ' . $mail_from,
    );

    $key = get_password_reset_key( $user );
    if ( is_wp_error( $key ) ) {
        return;
    }
    $url_password = network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user->user_login ) );

    $body = '<p>HTML body in your own style.</p>';
    $body .= '<p>It must include the login identifier: ' . $user->user_login . '</p>';
    $body .= '<p>And the link: ' . $url_password . '</p>';
    
    wp_mail( $mail_to, $subject, $body, $headers );
}

HTML 내용을 함수에 포함시키지 않으려면 템플릿 엔진을 사용하면 됩니다.위 코드에 추가할 수 있는 예시가 있습니다.

// Set up Mustache
$path = get_stylesheet_directory() . '/mails';
$dir  = wp_get_upload_dir();
$m    = new \Mustache_Engine( [
    'cache'           => $dir['basedir'] . '/mustache_cache',
    'loader'          => new \Mustache_Loader_FilesystemLoader( $path ),
    'partials_loader' => new \Mustache_Loader_FilesystemLoader( $path . '/layouts' ),
] );

// Variable data in the mail
$data['mail']['title'] = $subject;          // {{mail.title}}
$data['identifier']    = $user->user_login; // {{identifier}}
$data['url-password']  = $url_password;     // {{url-password}}

$body = $m->render( 'mail-template-new-user', $data );

콧수염 태그 설명서.

언급URL : https://stackoverflow.com/questions/13509575/how-to-send-email-password-when-creating-a-new-user-by-api-in-wordpress

반응형