Note that wp_set_auth_cookie()
will set cookies (using setcookie()
) which means there must be no output (HTML, spaces, empty lines, etc.) sent to the browser yet, or otherwise, the cookies will not be set or updated.
And I said that because by the time you call wp_insert_user()
, there has actually been an output sent to the browser, and the output is the whitespaces after the ?>
(PHP closing tag) in your code. For example, this part:
<?php if(isset($signUpError)){echo '<div>'.$signUpError.'</div>';}?>
<?php
So the whitespaces after the ?>
are actually sent to the browser, hence that causes setcookie()
to fail. Moreover, you’ve got an echo
above which indicates you’re not using the proper hook to auto-login (and redirect) the created user.
Therefore you should use an early hook such as template_redirect
to create the user and then logs the user in, and finally do the redirect. Here’s an example, just a basic one which hopefully would help you write your own or make your existing code works properly:
add_action( 'template_redirect', 'wpse_387961' );
function wpse_387961() {
// check if the form is submitted,
// clean and validate user input,
// define variables, etc etc.
// ... your code.
// create the user:
$user = wp_insert_user( $userdata );
if ( ! $user || is_wp_error( $user ) ) {
echo 'try again later..';
exit;
}
// auto-login the user:
wp_set_current_user( $user );
wp_set_auth_cookie( $user );
// then ensure the user is successfully logged-in
if ( (int) $user === get_current_user_id() ) {
// add item to the cart
// ... your code.
// then do the redirect:
wp_redirect( wc_get_checkout_url() );
exit;
} else { // this 'else' part is just for testing
echo 'auto-login failed?';
exit;
}
}
And actually, in your auto_login_new_user()
function, the $userid
is undefined (a typo, I guess?).. but anyway, you don’t need to use the user_register
hook. Just ensure and remember that when setting cookies via PHP and doing a redirect (using the PHP’s native header()
function which is used by wp_redirect()
), do not output anything to the browser!