Short answer – Your original function (mostly) works. This is your function edited to do what it needs to do:
function automatically_log_me_in( $user_id ) {
wp_set_current_user( $user_id );
wp_set_auth_cookie( $user_id );
wp_redirect( home_url( '/some-ending-page/' ) );
exit();
}
add_action( 'user_register', 'automatically_log_me_in' );
Long answer – here is an explanation of why this is the answer.
The suggestion of wp_signon()
won’t do it. You need the user credentials for that, and barring passing credentials, that function will attempt to retrieve the posted username (‘log’) and password (‘pwd’) from the form and I would assume ‘pwd’ would be lacking from that.
The other answers make suggestions that unfortunately don’t apply in this specific instance. Several are suggestions that are plugin specific. As the developer of one of those (WP-Members), as much as I’d like you to use that plugin, suggesting to use wpmem_post_register_data
doesn’t do you any good if you’re not using WP-Members.
Using wp_set_current_user()
as your original thought is the correct way to do it; but you need to redirect the user at the end so they are seen as logged in.
The user_register
action passes the ID of the just registered user, so I’m not sure why you would change the value of $user_id
by setting it to $user->ID
when you already have the value. And the only reason to get the user object in your original function is to get the username. This is an optional argument for wp_set_current_user()
and the wp_login
action so I wouldn’t even bother with that. (I’d ditch the wp_login
action because all that is doing is putting a hook into your process for outside functions to hook to. Whether you want/need this requires more information than your OP provides.) All that is just wasted bits in your code, IMO.
Does your registration process end at this point? The auth cookie is set and the user is logged in. However, that won’t be read until the next page request so you need to redirect the user to whatever page you want them to end on using wp_redirect()
after which you need to exit()
.