I have a form that creates a new user by using:
wp_create_user()
This works, but after this I want to auto log in the user.
I tried using:
$creds = array();
$creds['user_login'] = 'username';
$creds['user_password'] = 'password';
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ) {
$msg = $user->get_error_message();
die($msg);
} else {
$output_form = true;
}
But this creates a “headers already sent” error message because it’s not at the top of the page.
Is there a way to auto log in the user after I have created the user?
Here is a function I wrote that hooks into the gravity forms create user form but it can be added to whatever action hook your wp_create_user function is attached to.
The important part is
wp_set_auth_cookie
. This has to fire after the user is the best (only?) way to auto login a user without filling out the login form.You should probably use the action hook
init
to catch and process the registration form. This hook is called before anything is sent to the browser. If the form validates…wp_create_user
wp_signon
wp_redirect
to the page of your choice