問題描述

我正在使用 wp_login_form()在 jQuery 對話視窗中顯示登入表單。

如果使用者輸入錯誤的密碼,使用者將被帶到後端。我不想要有沒有辦法通知使用者他輸入錯誤的密碼,仍然保留在同一頁面上?

wp_login_form()來之前,我正在使用一個外掛。我希望我可以避免使用這個外掛。

我的程式碼:

wp_login_form( array(
  'label_remember' => __( 'Remember me' ),
  'label_log_in' => __( 'Login' )
) );

最佳解決方案

wp_login_form()建立一個具有 site_url/wp-login.php 的動作屬性的表單,這意味著當您單擊提交按鈕時,表單將釋出到 site_url/wp-login.php,它忽略了 redirect_to 上的錯誤 (如錯誤的密碼),因此在您的情況下,請返回使用外掛或重新建立整個登入過程以及您對錯誤的控制方式,看看 Check for correct username on custom login form 這是非常相似的問題。

次佳解決方案

我從谷歌來到這裡但答案並不滿足於我。我在尋找一段時間,找到一個更好的解決方案。

將其新增到您的 functions.php 中:

add_action( 'wp_login_failed', 'my_front_end_login_fail' );  // hook failed login

function my_front_end_login_fail( $username ) {
   $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
   // if there's a valid referrer, and it's not the default log-in screen
   if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
      wp_redirect( $referrer . '?login=failed' );  // let's append some information (login=failed) to the URL for the theme to use
      exit;
   }
}

第三種解決方案

目前我正在使用的方法來處理這裡概述的所有問題,甚至使用空白的使用者名稱/密碼,並不依賴於 javascript(儘管 js 可能會很好) 。

add_action( 'wp_login_failed', 'custom_login_failed' );
function custom_login_failed( $username )
{
    $referrer = wp_get_referer();

    if ( $referrer && ! strstr($referrer, 'wp-login') && ! strstr($referrer,'wp-admin') )
    {
        wp_redirect( add_query_arg('login', 'failed', $referrer) );
        exit;
    }
}

關鍵是這個過濾器可以更改如何處理空白的使用者名稱/密碼:

add_filter( 'authenticate', 'custom_authenticate_username_password', 30, 3);
function custom_authenticate_username_password( $user, $username, $password )
{
    if ( is_a($user, 'WP_User') ) { return $user; }

    if ( empty($username) || empty($password) )
    {
        $error = new WP_Error();
        $user  = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));

        return $error;
    }
}

您可以進一步透過將使用者重定向到您的自定義登入頁面並將該頁面用於 login_failed 重定向,從而進一步完全替代 wp-login.php 。全部程式碼:

/**
 * Custom Login Page Actions
 */
// Change the login url sitewide to the custom login page
add_filter( 'login_url', 'custom_login_url', 10, 2 );
// Redirects wp-login to custom login with some custom error query vars when needed
add_action( 'login_head', 'custom_redirect_login', 10, 2 );
// Updates login failed to send user back to the custom form with a query var
add_action( 'wp_login_failed', 'custom_login_failed', 10, 2 );
// Updates authentication to return an error when one field or both are blank
add_filter( 'authenticate', 'custom_authenticate_username_password', 30, 3);
// Automatically adds the login form to "login" page
add_filter( 'the_content', 'custom_login_form_to_login_page' );

/**
 * Custom Login Page Functions
 */
function custom_login_url( $login_url='', $redirect='' )
{
    $page = get_page_by_path('login');
    if ( $page )
    {
        $login_url = get_permalink($page->ID);

        if (! empty($redirect) )
            $login_url = add_query_arg('redirect_to', urlencode($redirect), $login_url);
    }
    return $login_url;
}
function custom_redirect_login( $redirect_to='', $request='' )
{
    if ( 'wp-login.php' == $GLOBALS['pagenow'] )
    {
        $redirect_url = custom_login_url();

        if (! empty($_GET['action']) )
        {
            if ( 'lostpassword' == $_GET['action'] )
            {
                return;
            }
            elseif ( 'register' == $_GET['action'] )
            {
                $register_page = get_page_by_path('register');
                $redirect_url = get_permalink($register_page->ID);
            }
        }
        elseif (! empty($_GET['loggedout'])  )
        {
            $redirect_url = add_query_arg('action', 'loggedout', custom_login_url());
        }

        wp_redirect( $redirect_url );
        exit;
    }
}
function custom_login_failed( $username )
{
    $referrer = wp_get_referer();

    if ( $referrer && ! strstr($referrer, 'wp-login') && ! strstr($referrer, 'wp-admin') )
    {
        if ( empty($_GET['loggedout']) )
        wp_redirect( add_query_arg('action', 'failed', custom_login_url()) );
        else
        wp_redirect( add_query_arg('action', 'loggedout', custom_login_url()) );
        exit;
    }
}
function custom_authenticate_username_password( $user, $username, $password )
{
    if ( is_a($user, 'WP_User') ) { return $user; }

    if ( empty($username) || empty($password) )
    {
        $error = new WP_Error();
        $user  = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));

        return $error;
    }
}
function custom_login_form_to_login_page( $content )
{
    if ( is_page('login') && in_the_loop() )
    {
        $output = $message = "";
        if (! empty($_GET['action']) )
        {
            if ( 'failed' == $_GET['action'] )
                $message = "There was a problem with your username or password.";
            elseif ( 'loggedout' == $_GET['action'] )
                $message = "You are now logged out.";
            elseif ( 'recovered' == $_GET['action'] )
                $message = "Check your e-mail for the confirmation link.";
        }

        if ( $message ) $output .= '<div class="message"><p>'. $message .'</p></div>';
        $output .= wp_login_form('echo=0&redirect='. site_url());
        $output .= '<a href="'.%20wp_lostpassword_url(%20add_query_arg('action',%20'recovered',%20get_permalink())%20)%20.'" title="Recover Lost Password">Lost Password?</a>';

        $content .= $output;
    }
    return $content;
}

自定義並新增它們以將徽標新增到 wp-login 頁面以進行密碼恢復:

// calling it only on the login page
add_action( 'login_enqueue_scripts', 'custom_login_css', 10 );
function custom_login_css() { wp_enqueue_style( 'custom_login_css', get_template_directory_uri() .'/library/css/login.css', false ); }
// changing the logo link from wordpress.org to your site
add_filter( 'login_headerurl', 'custom_login_logo_url' );
function custom_login_logo_url() { return home_url(); }
// changing the alt text on the logo to show your site name
add_filter( 'login_headertitle', 'custom_login_title' );
function custom_login_title() { return get_option('blogname'); }

登入徽標 css:

.login h1 a {
    background: url(../images/login-logo.png) no-repeat top center;
    width: 274px;
    height: 63px;
    text-indent: -9999px;
    overflow: hidden;
    padding-bottom: 15px;
    display: block;
}

編輯:我剛剛在另一個網站上實現了這個表格,發現上面的”step further” 更加完整,並修復了”add_actions” 中的小語法錯誤。新增了一些註釋和一種方法來自動將登入表單新增到登入頁面,而無需單獨的模板檔案。登入表單方法應該在大多數情況下工作,因為它附加到”the_content”,如果在登入頁面上有多個迴圈,則可能導致併發出,只需使用 page-login.php 模板即可。

第四種方案

SzczepanHołyszewski 關於接受解決方案中的空欄位的一個解決方案,以下 jQuery 將阻止進入標準的 wp-login 頁面:(新增到登入頁面模板或 footer.php)

jQuery("#loginform-custom").submit(function(){
     var isFormValid = true;
       jQuery("input").each(function()
       {
       if (jQuery.trim($(this).val()).length == 0){
       jQuery(this).addClass("submit_error");
       isFormValid = false;
       }
     else {
     jQuery(this).removeClass("submit_error");
     }
     });
     return isFormValid;
});

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。