Set user after wp_create_user?

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.

Read More

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?

Related posts

Leave a Reply

2 comments

  1. 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.

  2. 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…

    • Create the user with wp_create_user
    • Log in the user with wp_signon
    • Redirect the user using wp_redirect to the page of your choice