Skip to content

Instantly share code, notes, and snippets.

@tannerm
Last active November 9, 2015 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tannerm/5a9dc2ba7144287b0937 to your computer and use it in GitHub Desktop.
Save tannerm/5a9dc2ba7144287b0937 to your computer and use it in GitHub Desktop.
WordPress Ajax Login
jQuery(document).ready(function($){
'use strict';
var ajaxLogin = function() {
var SELF = this;
SELF.data = {'security': tm.security};
SELF.init = function(id) {
SELF.$loginContainer = $(id);
if ( ! SELF.$loginContainer.length ) {
return;
}
SELF.$form = SELF.$loginContainer.find('form');
SELF.$form.on('submit', SELF.handleSubmission);
};
SELF.handleSubmission = function(e){
e.preventDefault();
SELF.data['log'] = SELF.$loginContainer.find('form #user_login').val();
SELF.data['pwd'] = SELF.$loginContainer.find('form #user_pass').val();
SELF.$form.find('.error-message').remove();
SELF.$form.prepend('<p class="status-message">Logging in...</p>');
wp.ajax.send( 'tm_login', {
success: SELF.response,
data: SELF.data
} );
};
SELF.response = function(status) {
SELF.$form.find('.status-message').remove();
if ( status.success ) {
SELF.$form.prepend('<p class="success-message">Success! Reloading the page...</p>');
window.location.reload();
} else {
SELF.$form.prepend('<p class="error-message">' + status.message + '</p>');
}
};
};
var tmAjaxLogin = new ajaxLogin();
tmAjaxLogin.init('#login-form-modal');
});
<?php
new TM_Ajax_Login;
class TM_Ajax_Login {
static $success = false;
public function __construct () {
add_action( 'wp_ajax_tm_login', array( $this, 'ajax_login' ) );
add_action( 'wp_ajax_nopriv_tm_login', array( $this, 'ajax_login' ) );
}
public function ajax_login() {
$return['message'] = $this->login();
$return['success'] = self::$success;
return wp_send_json( $return );
}
public function login() {
// Do it this way to catch weird nonce issue.
if ( ! wp_verify_nonce( $_POST['security'], 'fu-ajax-login' ) ) {
wp_logout();
wp_send_json_error();
}
$status = wp_signon();
if ( is_wp_error( $status ) ) {
if ( 'incorrect_password' == $status->get_error_code() ) {
$message = sprintf( "The password you entered doesn't match our records. Please try again or <a href='%s' title='Password Lost and Found'>reset your password</a>.", wp_lostpassword_url() );
} else {
$message = str_replace( '<strong>ERROR</strong>: ', '', $status->get_error_message() );
}
return $message;
}
self::$success = true;
return $status;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment