Erik Andershed
Erik Andershed

Reputation: 383

Wordpress wp_signon() do not work in ajax call

I am trying to build an costum login to Wordpress in a AJAX call. I a remove the wp_signon() from the PHP function I do get the right echo. But then I add the wp_signon() it always return my whole login page in HTML. I can't see what I am doing wrong. And can't get the login to work.

Please help!

js

$.ajax({
    method: 'POST',
    url: '/wp-admin/admin-ajax.php',
    dataType: 'json',
    data: {
        'action': 'getLoggedIn',
        'user_name': user_name,
        'user_password': user_password,
        'user_remember': user_remember
    },
    success: function(response) {

        if (response === 'ok') {
            window.location = '/app/';

        } 

    },
    error: function(){}
});

PHP

function getLoggedIn() {

    global $wpdb;

    // Check if users is already logged in
    if ( is_user_logged_in() ) {
        echo 'You are already logged in';
        die;
    }

    //We shall SQL escape all inputs
    $username = $wpdb->escape($_REQUEST['user_name']);
    $password = $wpdb->escape($_REQUEST['user_password']);
    $remember = $wpdb->escape($_REQUEST['user_remember']);

    $creds = array();
    $creds['user_login'] = $username;
    $creds['user_password'] = $password;
    $creds['remember'] = $remember;
    $user_signon = wp_signon( $creds, false );

    // Check if error
    if ( is_wp_error($user_signon)) {
        echo $user_verify->get_error_code();
        exit();
    } else {
        echo 'ok';
        exit;
    }

    die();
}

add_action('wp_ajax_getLoggedIn', 'getLoggedIn');
add_action('wp_ajax_nopriv_getLoggedIn', 'getLoggedIn');

Upvotes: 0

Views: 1840

Answers (3)

farid teymouri
farid teymouri

Reputation: 191

try to make some custom user authenticate

add_filter('authenticate', function ($user, $username, $password) {
    if (empty($username) || empty($password)) {
        // get failed 
        do_action('wp_login_failed', $user);
    }
    return $user;
}, 10, 3);

// to handle even you can handle the error like
add_action('wp_login_failed', function ($username) {
    if (is_wp_error($username)) {
        // perform operation on error object for empty error
        return $username;
    }
});

Upvotes: 0

Erik Andershed
Erik Andershed

Reputation: 383

The problem was not the wp_signon() function. It was an other Wordpress action that redirects the page after user login has failed. This:

add_action( 'wp_login_failed', 'login_failed' );

Upvotes: 2

Syed Tahir Rasul
Syed Tahir Rasul

Reputation: 1

I got caught up in the same situation. did you remove that wp_login_failed action or how did you work this out?

Upvotes: -1

Related Questions