亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Start WordPress to reset password
Step 2: Redirect user to custom page
第 3 步:為 WordPress 更改密碼表單創(chuàng)建簡(jiǎn)碼
第 4 步:處理 WordPress 帳戶恢復(fù)表單提交
第 5 步:自定義 WordPress 更改密碼電子郵件
重置 WordPress 密碼
第 1 步:將用戶重定向到您的 WordPress 自定義密碼重置頁(yè)面
第 2 步:顯示 WordPress 更改密碼表單
第 3 步:處理 WordPress 重置密碼操作
結(jié)論
Home CMS Tutorial WordPress Building a Custom WordPress User Flow, Part Three: Password Reset

Building a Custom WordPress User Flow, Part Three: Password Reset

Sep 03, 2023 pm 11:05 PM
wordpress Construct reset Password

In the first two tutorials of this series, we built custom pages for logging in and registering new users. Now, there’s only one part of the login flow left to explore and replace: What happens if a user forgets their password and wants to reset their WordPress password?

In this tutorial we'll tackle the final step and complete the Personalized Login plugin we've built throughout the series.

The password reset feature in WordPress more or less follows the standard approach on websites today:

  1. The user initiates a reset by entering their username or email address and requesting WordPress to reset their password.
  2. Create a temporary password reset token and store it in user data. A link containing this token will be sent to the user's email address.
  3. The user clicks the link.
  4. On the reset password page, the token is verified and if it matches the user's data, they can choose a new password.

Just like login and new user registration, this functionality is handled through wp-login.php. So the general idea of ??how we customize this process is now mostly familiar from previous tutorials.

If you haven't read the first two tutorials, it's best to start with Part 1 and work your way through the series in order. You can follow the tutorial and code it yourself, or download the full source code from the linked GitHub repository.

Now, let's start replacing the first screen in the process.

Start WordPress to reset password

Resetting a WP password begins when a user arrives at your login page but cannot remember the password they used on the site.

To do this, we placed a Forgot your password? at the bottom of the Login form in the first part of this series. Message template link. By default, on a WordPress-powered site, this link points to wp-login.php?action=lostpassword, and the page looks like this:

Building a Custom WordPress User Flow, Part Three: Password Reset

To replace this page with a custom page, we will create a function to redirect the user to our custom page and hook the function into a WordPress action.

In this case, we have two options to choose from: we can use the action lost_password, which is called before the page is rendered, or the action we used in the previous tutorial: login_form_{action}, this time it is login_form_lostpassword.

There are two approaches we can take, but in order to limit the amount of unnecessary code executed, let's choose the latter option.

But first, let’s create a new WordPress custom password reset page:

Step 1: Create a reset password page p>

As you remember, in Part 1 we created a function that creates a WordPress page when the plugin is activated using the plugin_activated callback function.

In this function, the definition of the new page is added to the end of the $page_definitions array. In the WordPress password reset process, we also need a second page to select a new password. So to save time we are now also adding a second page.

For clarity, here is the entire array (with the last two page definitions added):

// Information needed for creating the plugin's pages
$page_definitions = array(
    'member-login' => array(
        'title' => __( 'Sign In', 'personalize-login' ),
        'content' => '[custom-login-form]'
    ),
    'member-account' => array(
        'title' => __( 'Your Account', 'personalize-login' ),
        'content' => '[account-info]'
    ),
    'member-register' => array(
        'title' => __( 'Register', 'personalize-login' ),
        'content' => '[custom-register-form]'
    ),
    'member-password-lost' => array(
        'title' => __( 'Forgot Your Password?', 'personalize-login' ),
        'content' => '[custom-password-lost-form]'
    ),
    'member-password-reset' => array(
        'title' => __( 'Pick a New Password', 'personalize-login' ),
        'content' => '[custom-password-reset-form]'
    )
);

The plugin activation callback is only called when the plugin is explicitly activated, so to create these new pages you must deactivate the plugin and then activate it again.

Now, after creating the page, we can redirect the user to member-password-lost instead of wp-login?action=lostpassword.

Step 2: Redirect user to custom page

As I mentioned above, we will use the action login_form_{action} or login_form_lostpassword to cut into .php before wp-login has a chance to render" Lost your password?" Default version. Screen.

In the plugin's constructor, add the following lines:

add_action( 'login_form_lostpassword', array( $this, 'redirect_to_custom_lostpassword' ) );

Then, create the function redirect_to_custom_lostpassword.

This function will check the request method: currently, we only operate on requests sent using the GET method, since these are the requests for displaying the screen. We'll see what happens with POST later.

/**
 * Redirects the user to the custom "Forgot your password?" page instead of
 * wp-login.php?action=lostpassword.
 */
public function redirect_to_custom_lostpassword() {
    if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
        if ( is_user_logged_in() ) {
            $this->redirect_logged_in_user();
            exit;
        }

        wp_redirect( home_url( 'member-password-lost' ) );
        exit;
    }
}

This function is actually the same function we used in the previous tutorial to redirect the user to the custom registration page, just replace the redirect with the page slug of the new page we created above (for some It's a good place to be) Maybe it will be refactored in the future? ).

現(xiàn)在,如果您在登錄頁(yè)面上點(diǎn)擊忘記了 WordPress 密碼?,您將被重定向到 WordPress 自定義密碼重置頁(yè)面。接下來(lái),讓我們創(chuàng)建一個(gè)短代碼來(lái)添加用于啟動(dòng)密碼重置的 WordPress 密碼表單。

第 3 步:為 WordPress 更改密碼表單創(chuàng)建簡(jiǎn)碼

在創(chuàng)建用于啟動(dòng) WordPress 密碼重置的頁(yè)面時(shí),我們將短代碼 [custom-lost-password-form] 添加到其正文中。現(xiàn)在,為了用表單替換短代碼,讓我們創(chuàng)建一個(gè)短代碼處理程序。

在插件的構(gòu)造函數(shù)中,添加以下行:

add_shortcode( 'custom-password-lost-form', array( $this, 'render_password_lost_form' ) );

然后,創(chuàng)建用于渲染表單的函數(shù):

/**
 * A shortcode for rendering the form used to initiate the password reset.
 *
 * @param  array   $attributes  Shortcode attributes.
 * @param  string  $content     The text content for shortcode. Not used.
 *
 * @return string  The shortcode output
 */
public function render_password_lost_form( $attributes, $content = null ) {
    // Parse shortcode attributes
    $default_attributes = array( 'show_title' => false );
    $attributes = shortcode_atts( $default_attributes, $attributes );

    if ( is_user_logged_in() ) {
        return __( 'You are already signed in.', 'personalize-login' );
    } else {
        return $this->get_template_html( 'password_lost_form', $attributes );
    }
}

現(xiàn)在,這個(gè)函數(shù)的大部分內(nèi)容你已經(jīng)很熟悉了:首先我們解析短代碼參數(shù)(show_title 用于決定是否應(yīng)該在啟動(dòng)密碼重置的表單之前呈現(xiàn)標(biāo)題) 。然后,如果用戶未登錄,該函數(shù)將呈現(xiàn)一個(gè)包含 WordPress 忘記密碼表單的模板。

現(xiàn)在讓我們添加該模板。在 templates 目錄中,創(chuàng)建一個(gè)新文件,并將其命名為 password_lost_form.php。然后,將以下代碼添加到該模板:

<div id="password-lost-form" class="widecolumn">
    <?php if ( $attributes['show_title'] ) : ?>
        <h3><?php _e( 'Forgot Your Password?', 'personalize-login' ); ?></h3>
    <?php endif; ?>

    <p>
        <?php
            _e(
                "Enter your email address and we'll send you a link you can use to pick a new password.",
                'personalize_login'
            );
        ?>
    </p>

    <form id="lostpasswordform" action="<?php echo wp_lostpassword_url(); ?>" method="post">
        <p class="form-row">
            <label for="user_login"><?php _e( 'Email', 'personalize-login' ); ?>
            <input type="text" name="user_login" id="user_login">
        </p>

        <p class="lostpassword-submit">
            <input type="submit" name="submit" class="lostpassword-button"
                   value="<?php _e( 'Reset Password', 'personalize-login' ); ?>"/>
        </p>
    </form>
</div>

如果 show_title 屬性設(shè)置為 true(第 2-4 行),模板首先顯示標(biāo)題。

接下來(lái)是關(guān)于第 6-13 行的一些說明和實(shí)際表格。正如您在第 15 行中看到的,表單將發(fā)布到 WordPress 函數(shù) wp_lostpassword_url 返回的網(wǎng)址,該網(wǎng)址與我們?cè)谥囟ㄏ蛴脩魰r(shí)在上面看到的網(wǎng)址相同到我們的自定義頁(yè)面。

此表單僅包含一個(gè)文本字段,user_login第 18 行)。在此字段中,默認(rèn)的 WordPress 重置密碼功能接受用戶的用戶名或電子郵件。由于我們使用電子郵件作為用戶名,因此它們是相同的,因此我們只要求字段標(biāo)簽中的電子郵件(第 17 行)。

添加此模板后,當(dāng)您點(diǎn)擊登錄頁(yè)面上的忘記密碼?消息模板鏈接時(shí),您將看到如下所示的頁(yè)面(如果使用 WordPress 默認(rèn)主題)就像二十十五

Building a Custom WordPress User Flow, Part Three: Password Reset

第 4 步:處理 WordPress 帳戶恢復(fù)表單提交

現(xiàn)在我們已經(jīng)創(chuàng)建了 WordPress 密碼表單,是時(shí)候看看用戶提交它時(shí)會(huì)發(fā)生什么了。

為了讓我們?cè)诓辉V諸黑客的情況下進(jìn)行正確的錯(cuò)誤處理,我們需要自己編寫一些功能 - 盡可能使用 wp-login.php 中的輔助函數(shù),自然。

為此,我們將在 login_form_lostpassword 操作中添加一個(gè)新函數(shù)來(lái)處理 POST 請(qǐng)求。

該函數(shù)將使用 retrieve_password 函數(shù)定義在 wp-login.php 中來(lái)查找用戶并啟動(dòng)密碼更新過程。然后,根據(jù)是否有錯(cuò)誤,該函數(shù)將用戶重定向到正確的頁(yè)面:如果出現(xiàn)錯(cuò)誤,則返回到忘記密碼? 消息模板頁(yè)面,成功后,進(jìn)入登錄頁(yè)面。

在構(gòu)造函數(shù)中,添加以下行:

add_action( 'login_form_lostpassword', array( $this, 'do_password_lost' ) );

然后,創(chuàng)建函數(shù):

/**
 * Initiates password reset.
 */
public function do_password_lost() {
    if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
        $errors = retrieve_password();
        if ( is_wp_error( $errors ) ) {
            // Errors found
            $redirect_url = home_url( 'member-password-lost' );
            $redirect_url = add_query_arg( 'errors', join( ',', $errors->get_error_codes() ), $redirect_url );
        } else {
            // Email sent
            $redirect_url = home_url( 'member-login' );
            $redirect_url = add_query_arg( 'checkemail', 'confirm', $redirect_url );
        }

        wp_redirect( $redirect_url );
        exit;
    }
}

該函數(shù)首先檢查請(qǐng)求方法(在第 5 行上)。由于我們對(duì)提交密碼丟失表單時(shí)的情況感興趣,因此該函數(shù)僅在找到 POST 請(qǐng)求時(shí)才會(huì)跳轉(zhuǎn)。 GET 請(qǐng)求已由我們之前創(chuàng)建的函數(shù) redirect_to_custom_lostpassword 處理。

然后,在第 6 行,我們調(diào)用 WordPress 函數(shù) retrieve_password。該函數(shù)的名稱有點(diǎn)誤導(dǎo):該函數(shù)并不真正檢索密碼,而是檢查表單中的數(shù)據(jù),然后通過創(chuàng)建重置 WP 密碼令牌并將其通過電子郵件發(fā)送給用戶,為 WordPress 密碼重置準(zhǔn)備用戶帳戶。< /p>

如果出現(xiàn)錯(cuò)誤(第 7 行),我們會(huì)將用戶重定向回頁(yè)面 member-password-lost,并將錯(cuò)誤代碼作為請(qǐng)求參數(shù)傳遞( 第 8-10 行,實(shí)際重定向在第 17 行完成)。

如果一切順利,用戶將被重定向到帶有請(qǐng)求參數(shù) checkemail 設(shè)置的登錄頁(yè)面(第 12-14 行),以便我們可以向用戶。

現(xiàn)在,如果您提交 WordPress 密碼表單,一切都應(yīng)該正常。但為了使用戶體驗(yàn)完整,我們需要返回到呈現(xiàn)丟失密碼和登錄表單的短代碼,并顯示錯(cuò)誤和成功通知。

讓我們從積極的方面開始,添加成功消息。

在短代碼函數(shù) render_login_form 中,在 get_template_html 調(diào)用之前添加以下行:

// Check if the user just requested a new password 
$attributes['lost_password_sent'] = isset( $_REQUEST['checkemail'] ) && $_REQUEST['checkemail'] == 'confirm';

在表單模板中,使用上面的屬性添加一條消息:

<?php if ( $attributes['lost_password_sent'] ) : ?>
    <p class="login-info">
        <?php _e( 'Check your email for a link to reset your password.', 'personalize-login' ); ?>
    </p>
<?php endif; ?>

現(xiàn)在,成功啟動(dòng)密碼重置后,登錄表單應(yīng)如下所示:

Building a Custom WordPress User Flow, Part Three: Password Reset

要顯示錯(cuò)誤,我們將返回到丟失的 WordPress 更改密碼表單。

首先,在短代碼處理程序 render_password_lost_form 中,在渲染模板之前,添加以下行以遍歷錯(cuò)誤代碼并收集數(shù)組 中匹配的錯(cuò)誤消息$attributes['errors']:

// Retrieve possible errors from request parameters
$attributes['errors'] = array();
if ( isset( $_REQUEST['errors'] ) ) {
    $error_codes = explode( ',', $_REQUEST['errors'] );

    foreach ( $error_codes as $error_code ) {
        $attributes['errors'] []= $this->get_error_message( $error_code );
    }
}

然后,在模板中,我們將呈現(xiàn)錯(cuò)誤:

<?php if ( count( $attributes['errors'] ) > 0 ) : ?>
    <?php foreach ( $attributes['errors'] as $error ) : ?>
        <p>
            <?php echo $error; ?>
        </p>
    <?php endforeach; ?>
<?php endif; ?>

最后,將錯(cuò)誤消息添加到我們的函數(shù) get_error_messages

// Lost password

case 'empty_username':
    return __( 'You need to enter your email address to continue.', 'personalize-login' );

case 'invalid_email':
case 'invalidcombo':
    return __( 'There are no users registered with this email address.', 'personalize-login' );

接下來(lái),為了完成密碼重置流程的第一步,我們來(lái)看看如何自定義發(fā)送給用戶的電子郵件。

第 5 步:自定義 WordPress 更改密碼電子郵件

正如我們之前看到的,當(dāng)發(fā)送重置 WP 密碼的請(qǐng)求時(shí),在函數(shù) retrieve_password 中,會(huì)發(fā)送一封 WordPress 更改密碼電子郵件,其中包含有關(guān)操作的快速說明和一個(gè)鏈接可用于完成密碼重置。

消息簡(jiǎn)短而切題。它完成了它應(yīng)該做的事情,但您可能想要對(duì)其進(jìn)行自定義以賦予其個(gè)人風(fēng)格,并可能使其更具描述性。

默認(rèn)文本被硬編碼在 wp-login.php 中,但在發(fā)送消息之前,WordPress 為插件開發(fā)人員提供了使用兩個(gè)過濾器替換它的機(jī)會(huì)。

首先,要替換消息正文,您可以使用過濾器 retrieve_password_message。我們現(xiàn)在就開始吧。

在插件的構(gòu)造函數(shù)中,添加以下行:

add_filter( 'retrieve_password_message', array( $this, 'replace_retrieve_password_message' ), 10, 4 );

然后,創(chuàng)建函數(shù) replace_retrieve_password_message

/**
 * Returns the message body for the password reset mail.
 * Called through the retrieve_password_message filter.
 *
 * @param string  $message    Default mail message.
 * @param string  $key        The activation key.
 * @param string  $user_login The username for the user.
 * @param WP_User $user_data  WP_User object.
 *
 * @return string   The mail message to send.
 */
public function replace_retrieve_password_message( $message, $key, $user_login, $user_data ) {
    // Create new message
    $msg  = __( 'Hello!', 'personalize-login' ) . "\r\n\r\n";
    $msg .= sprintf( __( 'You asked us to reset your password for your account using the email address %s.', 'personalize-login' ), $user_login ) . "\r\n\r\n";
    $msg .= __( "If this was a mistake, or you didn't ask for a password reset, just ignore this email and nothing will happen.", 'personalize-login' ) . "\r\n\r\n";
    $msg .= __( 'To reset your password, visit the following address:', 'personalize-login' ) . "\r\n\r\n";
    $msg .= site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user_login ), 'login' ) . "\r\n\r\n";
    $msg .= __( 'Thanks!', 'personalize-login' ) . "\r\n";

    return $msg;
}

該函數(shù)接收四個(gè)參數(shù):

  • $message 是發(fā)送給用戶的消息的默認(rèn)版本。我們將忽略此參數(shù)并從頭開始創(chuàng)建我們自己的文本。
  • $key 是用于驗(yàn)證用戶密碼重置請(qǐng)求的令牌。它需要包含在密碼重置鏈接中。
  • $user_login 是用戶的用戶名(在我們的例子中是電子郵件地址),密碼重置鏈接中也需要它。
  • $user_data 包含有關(guān)用戶的一些數(shù)據(jù)。我們暫時(shí)忽略這一點(diǎn),但如果您愿意,可以在自己的自定義中進(jìn)一步探索它。

大部分函數(shù)只是將消息創(chuàng)建為一系列字符串連接。用于完成密碼重置的 URL 是在第 18 行創(chuàng)建的。

為了進(jìn)行更完整的自定義,一種想法是添加一個(gè)設(shè)置字段來(lái)編輯密碼檢索消息的內(nèi)容,并使用它而不是以這種方式在函數(shù)內(nèi)編碼消息。

如果您愿意,可以使用過濾器 retrieve_password_title 以同樣的方式替換電子郵件標(biāo)題。過濾器函數(shù)采用一個(gè)參數(shù),即要發(fā)送給用戶的默認(rèn)標(biāo)題,并且應(yīng)返回新標(biāo)題。

進(jìn)一步自定義的另一種方法是替換整個(gè)消息并發(fā)送 HTML 消息,例如使用我在之前關(guān)于使用 Mandrill 從 WordPress 發(fā)送電子郵件的教程中解釋的方法。在這種情況下,我將使用 Mandrill API 在上面的過濾器函數(shù)中發(fā)送消息并返回 false,以便 WordPress 不會(huì)再次嘗試發(fā)送電子郵件。

您現(xiàn)在已經(jīng)完成了 WordPress 密碼重置過程的第一步:用戶可以要求重置 WP 密碼,該過程由 WordPress 啟動(dòng)。

接下來(lái),我們將了解當(dāng)用戶單擊 WordPress 更改密碼電子郵件中的鏈接時(shí)會(huì)發(fā)生什么。

重置 WordPress 密碼

正如我們?cè)谏厦婵吹降?,啟?dòng) WordPress 重置密碼后,用戶將被重定向回登錄頁(yè)面,并附有檢查電子郵件的說明。

在 WordPress 更改密碼電子郵件中,有一個(gè)返回 wp-login.php 的鏈接,其中參數(shù) loginkey 用于識(shí)別用戶并驗(yàn)證 WordPress 密碼重置請(qǐng)求。當(dāng)用戶單擊鏈接時(shí),WordPress 會(huì)驗(yàn)證用戶和密鑰的有效性,如果一切正常,則讓用戶設(shè)置新密碼。

該功能運(yùn)行良好,我們將使用其中的一部分,調(diào)用 wp-login.php 中的現(xiàn)有輔助函數(shù),但同樣,由于操作和過濾器在 WordPress 中的組織方式密碼重置代碼,我們必須重寫一些代碼才能完成定制。

第 1 步:將用戶重定向到您的 WordPress 自定義密碼重置頁(yè)面

首先,我們將首先將用戶重定向到我們自己的 WordPress 自定義密碼重置頁(yè)面(我們?cè)诒窘坛涕_始時(shí)創(chuàng)建的頁(yè)面)。

現(xiàn)在,您可能已經(jīng)熟悉了:與我們?cè)诘卿浐妥?cè)操作以及重置 WP 密碼流程中的第一頁(yè)中所做的相同,我們將使用操作 login_form_{action} 在 WordPress 執(zhí)行任何操作之前將密碼重置操作轉(zhuǎn)移到我們自己的自定義函數(shù)。

有兩個(gè) wp-login.php 操作用于相同的功能,rpresetpass,所以我們需要將它們重定向到同一函數(shù),redirect_to_custom_password_reset

在插件的構(gòu)造函數(shù)中,添加以下行:

add_action( 'login_form_rp', array( $this, 'redirect_to_custom_password_reset' ) );
add_action( 'login_form_resetpass', array( $this, 'redirect_to_custom_password_reset' ) );

然后,創(chuàng)建函數(shù):

/**
 * Redirects to the custom password reset page, or the login page
 * if there are errors.
 */
public function redirect_to_custom_password_reset() {
    if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
        // Verify key / login combo
        $user = check_password_reset_key( $_REQUEST['key'], $_REQUEST['login'] );
        if ( ! $user || is_wp_error( $user ) ) {
            if ( $user && $user->get_error_code() === 'expired_key' ) {
                wp_redirect( home_url( 'member-login?login=expiredkey' ) );
            } else {
                wp_redirect( home_url( 'member-login?login=invalidkey' ) );
            }
            exit;
        }

        $redirect_url = home_url( 'member-password-reset' );
        $redirect_url = add_query_arg( 'login', esc_attr( $_REQUEST['login'] ), $redirect_url );
        $redirect_url = add_query_arg( 'key', esc_attr( $_REQUEST['key'] ), $redirect_url );

        wp_redirect( $redirect_url );
        exit;
    }
}

該函數(shù)首先檢查這是一個(gè) GET 請(qǐng)求。 POST 發(fā)送到同一 URL 的請(qǐng)求將在下面處理。

然后,在第 8 行,我們調(diào)用 WordPress 函數(shù) check_password_reset_key 來(lái)驗(yàn)證通過重置 WP 密碼鏈接傳遞的參數(shù)是否有效。如果出現(xiàn)錯(cuò)誤,我們會(huì)將用戶重定向回登錄頁(yè)面,并將錯(cuò)誤代碼作為請(qǐng)求參數(shù)(第 9-16 行)。我們很快就會(huì)添加顯示錯(cuò)誤的代碼。

如果參數(shù)已成功驗(yàn)證并且允許用戶更新其密碼,該功能將繼續(xù)將用戶重定向到我們的 WordPress 自定義密碼重置頁(yè)面(仍為空)member-password-reset。

在第 19-20 行,我們將參數(shù) keylogin 添加到重定向 URL,以便其他人可以使用它們檢查用戶何時(shí)嘗試在下一個(gè)屏幕上設(shè)置新密碼。默認(rèn)版本的 WordPress 密碼重置使用 cookie,但為了教程的目的,我決定使用請(qǐng)求參數(shù)以使代碼更易于理解。

接下來(lái),讓我們創(chuàng)建一個(gè)自定義版本的重置 WordPress 密碼表單。

第 2 步:顯示 WordPress 更改密碼表單

點(diǎn)擊WordPress更改密碼電子郵件鏈接后向用戶顯示的重置WordPress密碼表單,默認(rèn)情況下如下所示:

Building a Custom WordPress User Flow, Part Three: Password Reset

這是一個(gè)簡(jiǎn)單的表單,有兩個(gè)字段,pass1pass2,一個(gè)用于輸入 WordPress 密碼,另一個(gè)用于重新輸入密碼以檢查是否有拼寫錯(cuò)誤。< /p>

要?jiǎng)?chuàng)建此表單的自定義版本,我們將使用短代碼。

首先,在插件的構(gòu)造函數(shù)中添加以下行:

add_shortcode( 'custom-password-reset-form', array( $this, 'render_password_reset_form' ) );

然后,創(chuàng)建用于渲染表單的函數(shù):

/**
 * A shortcode for rendering the form used to reset a user's password.
 *
 * @param  array   $attributes  Shortcode attributes.
 * @param  string  $content     The text content for shortcode. Not used.
 *
 * @return string  The shortcode output
 */
public function render_password_reset_form( $attributes, $content = null ) {
    // Parse shortcode attributes
    $default_attributes = array( 'show_title' => false );
    $attributes = shortcode_atts( $default_attributes, $attributes );

    if ( is_user_logged_in() ) {
        return __( 'You are already signed in.', 'personalize-login' );
    } else {
        if ( isset( $_REQUEST['login'] ) && isset( $_REQUEST['key'] ) ) {
            $attributes['login'] = $_REQUEST['login'];
            $attributes['key'] = $_REQUEST['key'];

            // Error messages
            $errors = array();
            if ( isset( $_REQUEST['error'] ) ) {
                $error_codes = explode( ',', $_REQUEST['error'] );

                foreach ( $error_codes as $code ) {
                    $errors []= $this->get_error_message( $code );
                }
            }
            $attributes['errors'] = $errors;

            return $this->get_template_html( 'password_reset_form', $attributes );
        } else {
            return __( 'Invalid password reset link.', 'personalize-login' );
        }
    }
}

該函數(shù)的核心從第 17 行開始,我們?cè)谄渲袡z查用戶識(shí)別參數(shù)登錄名和密鑰是否存在。如果不是,則密碼重置鏈接無(wú)效,我們只會(huì)呈現(xiàn)一條錯(cuò)誤消息(第 34 行)。

如果檢查正常,這兩個(gè)變量將添加到 $attributes 數(shù)組中,以使它們可用于表單模板(第 18-19 行)。

然后,在第 21-30 行,我們已經(jīng)使用本教程中早期表單中相同的錯(cuò)誤傳遞方法,為提交 WordPress 帳戶恢復(fù)表單時(shí)可能發(fā)生的錯(cuò)誤做好了準(zhǔn)備。

最后,在第 32 行,該函數(shù)讀取模板并將其返回到 WordPress 進(jìn)行渲染。

接下來(lái)讓我們創(chuàng)建模板。在 templates 目錄中,創(chuàng)建一個(gè)新文件,并將其命名為 password_reset_form.php。添加以下內(nèi)容:

<div id="password-reset-form" class="widecolumn">
    <?php if ( $attributes['show_title'] ) : ?>
        <h3><?php _e( 'Pick a New Password', 'personalize-login' ); ?></h3>
    <?php endif; ?>

    <form name="resetpassform" id="resetpassform" action="<?php echo site_url( 'wp-login.php?action=resetpass' ); ?>" method="post" autocomplete="off">
        <input type="hidden" id="user_login" name="rp_login" value="<?php echo esc_attr( $attributes['login'] ); ?>" autocomplete="off" />
        <input type="hidden" name="rp_key" value="<?php echo esc_attr( $attributes['key'] ); ?>" />
        
        <?php if ( count( $attributes['errors'] ) > 0 ) : ?>
            <?php foreach ( $attributes['errors'] as $error ) : ?>
                <p>
                    <?php echo $error; ?>
                </p>
            <?php endforeach; ?>
        <?php endif; ?>

        <p>
            <label for="pass1"><?php _e( 'New password', 'personalize-login' ) ?></label>
            <input type="password" name="pass1" id="pass1" class="input" size="20" value="" autocomplete="off" />
        </p>
        <p>
            <label for="pass2"><?php _e( 'Repeat new password', 'personalize-login' ) ?></label>
            <input type="password" name="pass2" id="pass2" class="input" size="20" value="" autocomplete="off" />
        </p>
        
        <p class="description"><?php echo wp_get_password_hint(); ?></p>
        
        <p class="resetpass-submit">
            <input type="submit" name="submit" id="resetpass-button"
                   class="button" value="<?php _e( 'Reset Password', 'personalize-login' ); ?>" />
        </p>
    </form>
</div>

表單以可選標(biāo)題開頭,如果簡(jiǎn)碼屬性 show_title 設(shè)置為 true(第 2-4 行),則顯示該標(biāo)題。

實(shí)際的形式緊跟在標(biāo)題之后。請(qǐng)注意,該表單將發(fā)布到 wp-login.php?action=resetpass第 6 行),與密碼重置電子郵件中的鏈接中使用的 URL 相同,但除外該電子郵件鏈接使用了簡(jiǎn)短版本 rp,而不是 resetpass。

在表單的開頭(第7-8行),我們?cè)O(shè)置了兩個(gè)隱藏字段rp_keyrp_login來(lái)傳遞keylogin 參數(shù)傳遞給表單處理程序,該處理程序?qū)⑹褂盟鼈儊?lái)驗(yàn)證密碼更改請(qǐng)求。

在第10-16行,模板將打印出錯(cuò)誤(如果有)。此代碼與本教程前面的短代碼模板中的代碼完全相同。

這兩個(gè)字段在18-25行中打印出來(lái),后面是一些有關(guān)選擇良好 WordPress 密碼的說明以及用于提交 WordPress 更改密碼表單的按鈕。

WordPress 更改密碼表單現(xiàn)在應(yīng)如下所示:

Building a Custom WordPress User Flow, Part Three: Password Reset

第 3 步:處理 WordPress 重置密碼操作

當(dāng)用戶通過單擊 WordPress 重置密碼按鈕提交表單時(shí),其內(nèi)容將發(fā)送到 wp-login.php?action=resetpass,相同的 URL我們?cè)谏厦媸褂昧藢⒂脩糁囟ㄏ虻轿覀兊淖远x密碼重置頁(yè)面。

當(dāng)然,當(dāng)我們自己創(chuàng)建表單時(shí),我們也可以使用不同的 URL。但是,通過保留此默認(rèn) URL 并使用 login_form_resetpass (和 login_form_rp,只是為了確定)操作來(lái)替換默認(rèn)功能,我們可以確保沒有人意外結(jié)束調(diào)用默認(rèn)版本的密碼重置。

為此,請(qǐng)?jiān)俅蜗驑?gòu)造函數(shù)添加兩行:

add_action( 'login_form_rp', array( $this, 'do_password_reset' ) );
add_action( 'login_form_resetpass', array( $this, 'do_password_reset' ) );

然后,創(chuàng)建函數(shù):

/**
 * Resets the user's password if the password reset form was submitted.
 */
public function do_password_reset() {
    if ( 'POST' == $_SERVER['REQUEST_METHOD'] ) {
        $rp_key = $_REQUEST['rp_key'];
        $rp_login = $_REQUEST['rp_login'];

        $user = check_password_reset_key( $rp_key, $rp_login );

        if ( ! $user || is_wp_error( $user ) ) {
            if ( $user && $user->get_error_code() === 'expired_key' ) {
                wp_redirect( home_url( 'member-login?login=expiredkey' ) );
            } else {
                wp_redirect( home_url( 'member-login?login=invalidkey' ) );
            }
            exit;
        }

        if ( isset( $_POST['pass1'] ) ) {
            if ( $_POST['pass1'] != $_POST['pass2'] ) {
                // Passwords don't match
                $redirect_url = home_url( 'member-password-reset' );

                $redirect_url = add_query_arg( 'key', $rp_key, $redirect_url );
                $redirect_url = add_query_arg( 'login', $rp_login, $redirect_url )
                $redirect_url = add_query_arg( 'error', 'password_reset_mismatch', $redirect_url );

                wp_redirect( $redirect_url );
                exit;
            }

            if ( empty( $_POST['pass1'] ) ) {
                // Password is empty
                $redirect_url = home_url( 'member-password-reset' );

                $redirect_url = add_query_arg( 'key', $rp_key, $redirect_url );
                $redirect_url = add_query_arg( 'login', $rp_login, $redirect_url );
                $redirect_url = add_query_arg( 'error', 'password_reset_empty', $redirect_url );

                wp_redirect( $redirect_url );
                exit;
            }

            // Parameter checks OK, reset password
            reset_password( $user, $_POST['pass1'] );
            wp_redirect( home_url( 'member-login?password=changed' ) );
        } else {
            echo "Invalid request.";
        }

        exit;
    }
}

該函數(shù)首先檢查請(qǐng)求方法,應(yīng)該是 POST; GET 請(qǐng)求已被上面的重定向函數(shù)處理。

然后,它從表單數(shù)據(jù)中收集密鑰和登錄參數(shù),并使用它們來(lái)驗(yàn)證第 9 行上的密碼重置鏈接,使用 WordPress 函數(shù) check_password_reset_key (我們已經(jīng)在重定向函數(shù)中使用了相同的函數(shù))。

第 10-18 行 中,我們?cè)俅螜z查密碼重置密鑰檢查中可能存在的錯(cuò)誤,將用戶重定向到忘記密碼?消息模板頁(yè)面進(jìn)行渲染的錯(cuò)誤。

然后,如果重置密鑰有效,我們可以專注于 WordPress 帳戶恢復(fù)表單。

首先,該函數(shù)檢查兩個(gè)密碼是否匹配(第 21-31 行),然后檢查它們是否為空(第 33-43 行)。在這兩種情況下,用戶都會(huì)被重定向回我們的密碼重置頁(yè)面,URL 中包含 keylogin 參數(shù),讓用戶重試密碼更新。

最后,如果所有檢查均成功(如果您愿意,可以隨意添加更多檢查),該函數(shù)將使用函數(shù) reset_password 重置 WordPress 密碼(位于 第 46 行) )并將用戶重定向到登錄頁(yè)面,并將參數(shù) password=changed 附加到 URL 以顯示通知。

WordPress 密碼現(xiàn)已成功更新,剩下的就是顯示成功通知并添加錯(cuò)誤消息。

首先,讓我們添加通知。在短代碼函數(shù) render_login_form 中,添加以下檢查:

// Check if user just updated password
$attributes['password_updated'] = isset( $_REQUEST['password'] ) && $_REQUEST['password'] == 'changed';

然后,在渲染表單之前將實(shí)際消息添加到模板 login_form.php

<?php if ( $attributes['password_updated'] ) : ?>
    <p class="login-info">
        <?php _e( 'Your password has been changed. You can sign in now.', 'personalize-login' ); ?>
    </p>
<?php endif; ?>

由于我們已經(jīng)添加了對(duì)呈現(xiàn)上述錯(cuò)誤消息的支持,剩下的就是將描述性錯(cuò)誤消息添加到我們的函數(shù) get_error_message 中。

switch...case 構(gòu)造中的 default 分支之前添加以下行:

// Reset password

case 'expiredkey':
case 'invalidkey':
    return __( 'The password reset link you used is not valid anymore.', 'personalize-login' );

case 'password_reset_mismatch':
    return __( "The two passwords you entered don't match.", 'personalize-login' );
    
case 'password_reset_empty':
    return __( "Sorry, we don't accept empty passwords.", 'personalize-login' );

結(jié)論

就是這樣!重置 WP 密碼功能已準(zhǔn)備就緒,因此我們現(xiàn)在已經(jīng)完成了 WordPress 登錄體驗(yàn)的自定義,從注冊(cè)新用戶到登錄并重置丟失的密碼。

我希望本系列為您提供了足夠的工具,以便您能夠更好地進(jìn)行進(jìn)一步的自定義(例如,通過向密碼重置流程添加新步驟),并更好地了解 wp-login.php 內(nèi)部發(fā)生的情況。

現(xiàn)在,去定制更多內(nèi)容!

The above is the detailed content of Building a Custom WordPress User Flow, Part Three: Password Reset. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

10 latest tools for web developers 10 latest tools for web developers May 07, 2025 pm 04:48 PM

Web development design is a promising career field. However, this industry also faces many challenges. As more businesses and brands turn to the online marketplace, web developers have the opportunity to demonstrate their skills and succeed in their careers. However, as demand for web development continues to grow, the number of developers is also increasing, resulting in increasingly fierce competition. But it’s exciting that if you have the talent and will, you can always find new ways to create unique designs and ideas. As a web developer, you may need to keep looking for new tools and resources. These new tools and resources not only make your job more convenient, but also improve the quality of your work, thus helping you win more business and customers. The trends of web development are constantly changing.

How to import the source code of wordpress How to import the source code of wordpress Apr 20, 2025 am 11:24 AM

Importing WordPress source code requires the following steps: Create a sub-theme for theme modification. Import the source code and overwrite the files in the sub-topic. Activate the sub-theme to make it effective. Test the changes to make sure everything works.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

How to add your WordPress site in Yandex Webmaster Tools How to add your WordPress site in Yandex Webmaster Tools May 12, 2025 pm 09:06 PM

Do you want to connect your website to Yandex Webmaster Tools? Webmaster tools such as Google Search Console, Bing and Yandex can help you optimize your website, monitor traffic, manage robots.txt, check for website errors, and more. In this article, we will share how to add your WordPress website to the Yandex Webmaster Tool to monitor your search engine traffic. What is Yandex? Yandex is a popular search engine based in Russia, similar to Google and Bing. You can excel in Yandex

How to set, get and delete WordPress cookies (like a professional) How to set, get and delete WordPress cookies (like a professional) May 12, 2025 pm 08:57 PM

Do you want to know how to use cookies on your WordPress website? Cookies are useful tools for storing temporary information in users’ browsers. You can use this information to enhance the user experience through personalization and behavioral targeting. In this ultimate guide, we will show you how to set, get, and delete WordPresscookies like a professional. Note: This is an advanced tutorial. It requires you to be proficient in HTML, CSS, WordPress websites and PHP. What are cookies? Cookies are created and stored when users visit websites.

How to fix HTTP image upload errors in WordPress (simple) How to fix HTTP image upload errors in WordPress (simple) May 12, 2025 pm 09:03 PM

Do you need to fix HTTP image upload errors in WordPress? This error can be particularly frustrating when you create content in WordPress. This usually happens when you upload images or other files to your CMS using the built-in WordPress media library. In this article, we will show you how to easily fix HTTP image upload errors in WordPress. What is the reason for HTTP errors during WordPress media uploading? When you try to upload files to Wo using WordPress media uploader

How to register a wordpress account How to register a wordpress account Apr 20, 2025 am 11:45 AM

To create an account on WordPress, simply visit its website, select the registration option, fill in the registration form, and verify your email address. Other ways to register include using a Google account or Apple ID. The benefits of signing up include creating a website, gaining features, joining the community, and gaining support.

See all articles