잘못된 비밀번호를 입력 한 후 사용자를 어떻게 리디렉션합니까?


16

wp_login_form()jQuery 대화 상자 창에 로그인 양식을 표시 하는 데 사용 하고 있습니다.

사용자가 잘못된 비밀번호를 입력하면 백엔드로 이동합니다. 나는 그것을 원하지 않습니다. 사용자에게 잘못된 비밀번호를 입력했지만 여전히 같은 페이지에 남아 있음을 알리는 방법이 있습니까?

오기 전에 wp_login_form()플러그인을 사용하고있었습니다. 나는 이것을 위해 플러그인을 사용하지 않기를 바라고 있습니다.

내 코드 :

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

답변:



26

나는 구글에서 왔어요. 그러나 대답은 나를 만족시키지 못했습니다. 나는 잠시 찾고 있었고 더 나은 해결책을 찾았습니다.

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;
   }
}

감사합니다 Alexey, 나는 이것을 테스트 할 것입니다 (여전히 플러그인을 사용하고 있습니다)
Steven

7
Alexey의 솔루션은 잘못된 자격 증명을 입력하면 작동하지만 사용자가 사용자 이름 또는 비밀번호 입력을 잊어 버린 경우 불행히도 실패합니다. 분명히이 경우 Wordpress는 사용자를 로그인하려고 시도하지 않으므로 wp_login_failed 작업이 수행되지 않습니다.
Szczepan Hołyszewski

wp_get_referer ()를 사용하여 시간을 절약하십시오. codex.wordpress.org/Function_Reference/wp_get_referer
Jake

1
또한 여기에서 add_query_arg를 확실히 사용하므로 wp_redirect는 "wp_redirect (add_query_arg ( 'login', 'failed', $ referrer));"이어야합니다.
Jake

18

여기에 설명 된 모든 문제를 처리하기 위해 현재 사용중인 방법은 빈 사용자 이름 / 암호로도 훌륭하게 작동하며 자바 스크립트에 의존하지 않습니다 (j는 이것과 함께 좋을 수도 있지만).

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="'. wp_lostpassword_url( add_query_arg('action', 'recovered', get_permalink()) ) .'" 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;
}

편집 : 방금 다른 사이트 양식 스크래치에서 이것을 구현하고 위의 "추가 단계"가 더 완벽하다는 것을 발견하고 "add_actions"에서 작은 구문 오류를 수정했습니다. 별도의 템플릿 파일없이 로그인 페이지에 로그인 양식을 자동으로 추가하는 방법과 설명이 추가되었습니다. 로그인 양식 메소드는 "the_content"에 첨부되어 있기 때문에 대부분의 경우 작동해야합니다. 로그인 페이지에 둘 이상의 루프가있는 경우이 문제가 발생할 수 있습니다.이 경우 page-login.php 템플리트를 사용하십시오.


1
감사합니다. 이것에 대해 살펴 보겠습니다 (Twitter 및 FB와 같은 타사 로그인과 함께 작동하도록 할 수 있는지 확인)
Steven

1
Jake-이것은 훌륭한 완벽한 솔루션입니다. 공유해 주셔서 감사합니다. +1
henrywright

이것은 기본적으로 아주 완벽한 작은 플러그인 인 Sewn In Template Login이라는 플러그인으로 포장되어 있습니다. wordpress.org/plugins/sewn-in-template-log-in
Jake

유일한 문제는 실제로 프론트 엔드에서 오류를 발생시키지 않는다는 것입니다.
Siyah

4

허용 된 솔루션의 빈 필드에 대한 Szczepan Hołyszewski의 요점에 대한 솔루션 인 다음 jQuery는 표준 wp 로그인 페이지로 이동하지 못하게합니다 (로그인 페이지 템플릿 또는 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;
});

0

Alexey의 답변에 하나 추가. 필드 중 하나가 비어 있지 않은지 확인하기 위해 jquery 함수를 추가 할 수 있습니다. 이렇게하면 확인할 사항이 없으면 양식이 제출되지 않으므로 WordPress가 /wp-login.php로 리디렉션되지 않습니다.

  <script>
        $("#wp-submit").click(function() {
          var user = $("input#user_login").val();
            if (user == "") {
            $("input#user_login").focus();
            return false;
          }
         });
  </script>   

여전히 잊어 버린 암호 측면을 수정하는 방법을 잘 모르겠습니다


3
WordPress는 "충돌 없음"모드에서 jQuery를로드합니다. $별명이 작동하지 않습니다.
s_ha_dum

또한 사용자가 로그인 버튼을 클릭하지 않고 [입력]을 누르는 것을 고려해야합니다. 또한 빈 암호도 확인해야합니다.
Steven

-1
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;
});

제발 편집 답변을 하고, 설명을 추가 : 문제를 해결할 수있는?
fuxia
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.