How to auto login after registration?

by gloom   Last Updated May 15, 2019 22:08 PM

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 ) {
    $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( '' )";
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!!

Related Questions

Updated June 17, 2016 08:03 AM

Updated October 30, 2018 15:08 PM

Updated January 09, 2018 13:08 PM

Updated September 17, 2017 18:08 PM

Updated June 29, 2019 17:08 PM