How can I login a user programmatically in to WordPress?

I’m working on a custom WordPress plugin and I need to be able to programmatically log a user in. I’ve tried using the wp_signon function, but it requires the user’s password. I want to log the user in without requiring their password. Do you know of any other ways I can log a user in programmatically in WordPress? I’d really appreciate any guidance you can provide!

To login a user programmatically in WordPress, you can use the wp_set_current_user function. This function allows you to set the current user by ID and bypass the login process, effectively logging the user in. Check the example code below.

$user_id = 1234;
$user = get_user_by( 'id', $user_id ); 
if( $user ) {
    wp_set_current_user( $user_id, $user->user_login );
    wp_set_auth_cookie( $user_id );
    do_action( 'wp_login', $user->user_login );
}

You can redirect the user to home right after login, just by adding the below code.

wp_safe_redirect( home_url('/') );
exit();