問題描述
我用密碼保護了一個頁面。當插入的密碼不正確時,我想新增一個簡短的錯誤訊息。
我該怎麼做?
我新增這個程式碼來顯示和自定義我的頁面上的表單。
我的 functions.php
add_filter( 'the_password_form', 'custom_password_form' );
function custom_password_form() {
global $post;
$label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );
$o = '<form class="protected-post-form" action="' . get_option('siteurl') . '/wp-pass.php" method="post">' .
'<p class="glossar-form-p">Alle weiteren Glossarbeiträge sind durch ein Passwort geschützt. </p>' .
' <label for="' . $label . '">' . ' </label><input name="post_password" id="' . $label . '" type="password" size="20" />
<input type="submit" name="Submit" value="' . esc_attr__( "Login" ) . '" />
</form>
';
return $o;
}
最佳解決方案
最新輸入的密碼作為安全雜湊儲存在名為'wp-postpass_' . COOKIEHASH 的 cookie 中。
當密碼錶單被呼叫時,該 cookie 已被 WordPress 驗證。所以你只需要檢查該 cookie 是否存在:如果它和密碼錶單顯示,密碼是錯誤的。
add_filter( 'the_password_form', 'wpse_71284_custom_post_password_msg' );
/**
* Add a message to the password form.
*
* @wp-hook the_password_form
* @param string $form
* @return string
*/
function wpse_71284_custom_post_password_msg( $form )
{
// No cookie, the user has not sent anything until now.
if ( ! isset ( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) )
return $form;
// Translate and escape.
$msg = esc_html__( 'Sorry, your password is wrong.', 'your_text_domain' );
// We have a cookie, but it doesn』t match the password.
$msg = "<p class='custom-password-message'>$msg</p>";
return $msg . $form;
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。