Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
Works if I add this right after the creation: wp_set_current_user($user_id); –  redconservatory Aug 5 '11 at 15:44
add comment

2 Answers

up vote 2 down vote accepted

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.

share|improve this answer
add comment

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
share|improve this answer
    
Thanks but as I mentioned in my question I am getting a error message with wp_signon if I don't put it at the beginning of the page...trying to stay on the same page if possible. –  redconservatory Aug 5 '11 at 15:42
    
The point is that you have do wp_signon before output, since that function sets headers. You have to deal with the form submission before WP starts rendering the page. –  Chris Carson Aug 5 '11 at 15:53
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.