2017-01-18 93 views
1

我想開發一個WordPress的登錄Ajax表單。似乎這個插件工作正常。如果我插入正確的用戶名和密碼登錄正常工作,並顯示正確的消息,然後重定向到正確的頁面,但如果我輸入用戶名和密碼不正確的值沒有發生,並且錯誤消息不會出現。WordPress的Ajax登錄錯誤消息

似乎函數is_wp_error不會回顯錯誤。

你知道爲什麼嗎?在我的代碼下面

謝謝。

PHP

function ajax_login_init(){ 
wp_enqueue_script('ajax-login', get_template_directory_uri() . '/js/jquery.ajax.login.js', array('jquery') , $ver , true); 
wp_localize_script('ajax-login', 'loginajax', array('ajaxurl' => admin_url('admin-ajax.php'),)); 
// Enable the user with no privileges to run ajax_login() in AJAX 
add_action('wp_ajax_nopriv_met_login_member', 'met_login_member'); 
} 

if (!is_user_logged_in()) { 
add_action('init', 'ajax_login_init'); 

} 

function met_login_member() { 
    $user_login  = $_POST['met_user_login']; 
    $user_pass  = $_POST['met_user_pass']; 

    if(!check_ajax_referer('ajax-login-nonce', 'login-security', false)) { 
     echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Session token has expired, please reload the page and try again', 'met').'</div>')); 
    } 

    else if(empty($user_login) || empty($user_pass)){ 
     echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Please fill all form fields', 'met').'</div>')); 
    } else { // Now we can insert this account 

     $creds = array(); 
     $creds['user_login'] = $user_login; 
     $creds['user_password'] = $user_pass; 
     $creds['remember'] = true; 
     $user = wp_signon($creds, false); 

     if(is_wp_error($user)) { 
      echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.$user->get_error_message().'</div>')); 
     } else { 
      echo json_encode(array('error' => false, 'message'=> '<div class="alert alert-success">'.__('Login successful, reloading page...', 'met').'</div>')); 
     } 
    } 

    die(); 
} 

HTML

<div class="user-modal"> 

     <div class="user-modal-container"> 

      <ul class="switcher"> 

       <li><span><?php _e('Sign in', 'met'); ?></span></li> 

       <li><span><?php _e('New Account', 'met'); ?></span></li> 

      </ul> 

      <div class="modal-login"> 

       <form id="login-form" class="modal-form" action="<?php echo home_url('/'); ?>" method="post" /> 

        <p class="fieldset"> 

         <label class="image-replace email" for="signin-email"><?php _e('Username', 'met'); ?></label> 

         <input id="user-login" class="full-width has-padding has-border" type="text" name="met_user_login" placeholder="<?php _e('Username', 'met'); ?>" value="" size="20" tabindex="10" required /> 

        </p> 

        <p class="fieldset"> 

         <label class="image-replace password" for="signin-password"><?php _e('Password', 'met'); ?></label> 

         <input id="user-pass" class="full-width has-padding has-border" type="password" name="met_user_pass" placeholder="<?php _e('Password', 'met'); ?>" value="" size="20" tabindex="20" required /> 

         <span class="show-password"><?php _e('Show', 'met'); ?></span> 

        </p> 

        <p class="fieldset"> 

         <label class="checkbox" for="rememberme"> 

          <input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90"><?php _e('Remember me', 'met'); ?> 

         </label> 

        </p> 

        <p class="fieldset"> 

         <button id="wp-submit" class="full-width" data-loading-text="<?php _e('Loading...', 'met') ?>" type="submit"><?php _e('Sign In', 'met'); ?></button> 

         <input type="hidden" name="action" value="met_login_member" /> 

        </p> 

        <?php wp_nonce_field('ajax-login-nonce', 'login-security'); ?> 

       </form> 

       <div class="errors"></div> 

       <p class="modal-form-bottom-message"><span><?php _e('Lost your password?', 'met'); ?></span></p> 

      </div> 

    </div> 
</div> 

JS

$('button').on('click', function(e) { 

    e.preventDefault(); 

    $.post(loginajax.ajaxurl, $('#login-form').serialize(), function(data) { 

     var obj = $.parseJSON(data); 

     $('.modal-login .errors').html(obj.message); 

     if(obj.error === false) { 
      window.location.reload(true); 
     } else if(obj.error === true) { 
      $('.alert-danger').delay(2000).fadeOut('slow',function(){$(this).hide();}); 
     } 


    }); 

}); 
+0

您是否嘗試過在回覆每條消息後放置die()函數? - 我詳細闡述了你的功能,請檢查答案,並讓我知道你是否有任何問題。 –

回答

0

看來你是在朝着正確的方向。爲了填補一些空白,我對代碼做了一些更改。強烈建議在WordPress中提交敏感(或任何)數據時,清理從$POST收集的所有數據。

此外,我們正在驗證收集的憑證,只需檢查是否存在用戶名或電子郵件,如果檢查無誤,我們會定義在成功登錄時驗證用戶身份所需的用戶數據,當直接訪問/wp-admin/時也會登錄到管理儀表板。我們通過清除任何舊的身份驗證Cookie併爲當前用戶設置新的身份驗證碼來完成此操作。

儘管這裏沒有什麼新東西,但這些步驟已被證明可以減少在通過WordPress中的Ajax驗證用戶身份時最常見的問題。

我測試過這個函數,它似乎沒有與is_wp_error()拋出的錯誤信息有關的問題。另外,我添加了一個可選的簡單方法來捕獲最常見的錯誤消息,然後自定義這些消息。我希望它能讓你和它一起前進!

function met_login_member() { 

// First check the nonce, if it fails the function will break 
if(!check_ajax_referer('ajax-login-nonce', 'login-security')) { 

    echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Session token has expired, please reload the page and try again', 'met').'</div>')); 

    die(); 

} 

// Nonce is checked, get the POST data and sign the user on 
$creds = array(); 
$creds['user_login'] = !empty($_POST['met_user_login']) ? sanitize_user(trim($_POST['met_user_login'])) : NULL; 
$creds['user_password'] = !empty($_POST['met_user_pass']) ? sanitize_text_field(trim($_POST['met_user_pass'])) : NULL; 
$creds['remember'] = true; 

// Pass login details through wp_signon() 
// wp_signon() accepts an optional boolean parameter false OR true, whether to use a secure cookie in case of running a website over SSL. 
$user_creds = wp_signon($creds, false); 

$user_login  = (string) sanitize_user($_POST['met_user_login']); 
$user_pass  = (string) sanitize_text_field(trim($_POST['met_user_pass'])); 

// ---- CHECK IF USERNAME OR EMAIL EXISTS ---- // 
if (username_exists($user_login)) { 

    $user_exists = (bool) true; 
    $user  = (object) get_user_by('login', $user_login); 

} elseif (email_exists($user_login)) { 

    $user_exists = (bool) true; 
    $user  = (object) get_user_by('email', $user_login); 

} else { 

    $error = new WP_Error('no_user_found', 'Username or Email was not found, please try again', 'Page Data'); 

    //echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Username or Email was not found, please try again', 'met').'</div>')); 
    //die(); 

} // end else 

if ($user_exists === (bool) true) { 

    // Define user data 

    $user_id = $user->ID; 
    $user_data = get_userdata($user_id); 

    $username = $user_data->user_login; 
    $userpass = $user_data->user_pass; 

} 

// ---- CHECK FOR EMPTY/INCORRECT DATA ---- // 
if(empty($user_login) && empty($user_pass)){ 

    echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('The username and password cannot be empty', 'met').'</div>')); 
    die(); 

} elseif (is_wp_error($user_signon)) { 

    echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.$user_signon->get_error_message().'</div>')); 
    die(); 

    // Optionally catch & customize error messages 

    // $signon_errors = $user_creds->get_error_codes(); 

    // if (in_array('invalid_username', $signon_errors)) { 
    //  echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Wrong username or email', 'met').'</div>')); 
    //  die();  

    // } elseif (in_array('empty_username', $signon_errors)) { 
    //  echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('The username or email cannot be empty', 'met').'</div>')); 
    //  die(); 

    // } elseif (in_array('empty_password', $signon_errors)) { 
    //  echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('The password field cannot be empty', 'met').'</div>')); 
    //  die(); 

    // } elseif (in_array('incorrect_password', $signon_errors)) { 
    //  echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Wrong password', 'met').'</div>')); 
    //  die(); 

    // } else { 
    //  echo json_encode(array('error' => true, 'message'=> '<div class="alert alert-danger">'.__('Wrong username or password', 'met').'</div>')); 
    //  die(); 

    // } 

} else { 

    wp_clear_auth_cookie(); 
    wp_set_current_user($user_id, $username); 
    wp_set_auth_cookie($user_id); 

    echo json_encode(array('error' => false, 'message'=> '<div class="alert alert-success">'.__('Login successful, reloading page...', 'met').'</div>')); 

    die(); 

} 

    die(); 

}