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?

2 Answers
2

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.

function my_auto_login( $user_id ) {
    wp_set_auth_cookie( $user_id, false, is_ssl() );
    wp_redirect( admin_url( 'profile.php' ) );
    exit;
}

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.

Tags:

Leave a Reply

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