0

I create an user using

 $user_id = wp_create_user($username, $password, $email);

After creating the user I want them to auto login and so according to ravi patel, I have added the following code in my functions.php.

function auto_login_new_user( $user_id ) {
    wp_set_current_user($user_id);
    wp_set_auth_cookie($user_id);
    $user = get_user_by( 'id', $user_id );
    do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1]
    wp_redirect( home_url() ); // You can change home_url() to the specific URL,such as "wp_redirect( 'http://www.wpcoke.com' )";
    exit;
}
add_action( 'user_register', 'auto_login_new_user' );

But as expected, the following warning popped up.


Warning: Cannot modify header information - headers already sent by (output started at /opt/lampp/htdocs/vuewordpress/wp-includes/link-template.php:3840) in /opt/lampp/htdocs/vuewordpress/wp-includes/pluggable.php on line 928

How do I get rid off this and redirect the user on the same page from they try to sign up?

I understand one thing the I need to run the code before the header is written. May be I need to somehow hook this action in init. But I dont know how to do it.

Any help is highly appreciable!!

  • You'd need to share the code responsible for creating users – Ali_k May 16 '19 at 1:23
1

Have you tried this?

function auto_login_new_user( $user_id ) {
    wp_set_current_user($user_id);
    wp_set_auth_cookie($user_id);
    wp_redirect( home_url() ); // You can change home_url() to the specific URL,such as "wp_redirect( 'http://www.wpcoke.com' )";
    exit();
}
add_action( 'user_register', 'auto_login_new_user' );

Taken from this SO answer: WordPress auto login after registration not working

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