Ajax login WordPress.

Sometime we need to login in site without reloading the page.so we simply use ajax for it. first we add login form in html than register a ajax path and than use jquery execute process.
1. Form Html using wp_footer hook
# add ajax login form to page

add_action( 'wp_footer', 'CustomLoginHtml' );
function CustomLoginHtml() {
  if (!is_user_logged_in()) {
  $actual_link = (isset($_SERVER['HTTPS'])?"https":"http")."://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  ob_start();
  ?>
  <form id="login" class="buyback-ajax-auth" action="login" method="post">
    <div class="title-text">Login</div>
    <p class="status"></p>
    <?php echo wp_nonce_field('ajax-login-nonce', 'security', true, false);?>
    <label for="username">Username</label>
    <input id="username" type="text" class="required" name="username">
    <label for="password">Password</label>
    <input id="password" type="password" class="required" name="password">
    <div class="cf">
    <input class="submit_button" type="submit" value="LOGIN">
    </div>
    <a class="login_close" href="">×</a>
    <input id="redirectto" type="hidden" value="'.$actual_link.'">
    </form>
  <?php
  echo ob_get_clean();
  }
}

2. Ajax Define

add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
function ajax_login(){
  check_ajax_referer( 'ajax-login-nonce', 'security' );
  auth_user_login($_POST['username'], $_POST['password'], 'Login');
  die();
}
function auth_user_login($user_login, $password, $login){
    $info = array();
    $info['user_login'] = $user_login;
    $info['user_password'] = $password;
    $info['remember'] = true;
    $user_signon = wp_signon( $info, false );
    if ( is_wp_error($user_signon) ){
      echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
    } else {
      wp_set_current_user($user_signon->ID);
      echo json_encode(array('loggedin'=>true, 'message'=>__($login.' successful, redirecting...')));
    }
  die();
}

3. Jquery

add_action( 'wp_footer', 'CustomLoginJquery' );
function CustomLoginJquery() {
  ?>
<script>
  jQuery(window).load(function () {
    jQuery("form#login").on("submit", function (e) {
      return ajaxLogin(this), e.preventDefault(), !1
    })
  });
  var siteurl = <?php echo site_url();?>;
  function ajaxLogin(e) {
    if (jQuery.isFunction(jQuery.fn.valid) && !jQuery(e).valid()) return !1;
    jQuery("p.status", e).show().text(siteurl.loadingmessage),
    action = "ajaxlogin",
    username = jQuery("form#login #username").val(),
    redirectto = jQuery("form#login #redirectto").val(),
    password = jQuery("form#login #password").val(),
    email = "",
    security = jQuery("form#login #security").val(),
    ctrl = jQuery(e),
    jQuery.ajax({
      type: "POST",
      dataType: "json",
      url: siteurl + "/wp-admin/admin-ajax.php?action=" + action,
      data: {
        username: username,
        password: password,
        email: email,
        security: security
      },
      success: function (e) {
        console.log(e), jQuery("p.status", ctrl).text(e.message), 1 == e.loggedin && (document.location.href = redirectto)
      }
    })
  }
</script>
  <?php
}

Enjoy

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top