Does anybody have any experience writing a custom Wordpress login page using the functions:
wp_signon()
and wp_set_auth_cookie()
found on http://codex.wordpress.org/Function_Reference/
I can't seem to get them working.
The code looks something like this:
function login_wordpress($username, $password) {
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ) {
echo $user->get_error_message();
die();
} else {
wp_set_auth_cookie( $user, 0, 0);
}
}
Am I missing something basic?
You need to change this line:
To this:
$user
is aWP_User
Object not user id.wp_signon
returnsWP_Error
on failure, orWP_User
on success.Was having real trouble myself... finally got it to work..!! (after several days of experimenting and banging my head against it)
One thing to make sure is that you haven't sent any output yet or the session cookie won't write as it needs to be in the header. Also if you call wp_signon before the session starts, there session info gets lost also... sheesh... strange but I had both happening to me. Anyhoo no more ado...
// Create new user (for example)
// Make sure username is up to date... I needed this as there was a hook to user_register being called in wp_insert_user but that hook is called after the user is created, so it needed a DB cache clear to work otherwise the wrong username was set... So the user was auto-logged in for one page only - ridiculous. (It was Register Plus Redux doing the hooking btw.)
// Make sure user session has started
// Login Current User
// Check it worked
I did this in a project a few years ago, so the Wordpress code was a bit different. But this code worked for me:
I didn't have to use wp_signon at all, but that may have changed.
Are you getting an error message, or what do you see when you run your code?