wordpress login user programmatically
Use the following code to programmatically login a user in WordPress:
// Get the user information based on the username
$user = get_user_by( 'login', 'username' );
// Log in the user
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID );
do_action( 'wp_login', $user->user_login );
Explanation:
1. The get_user_by()
function retrieves the user based on the username provided.
2. wp_set_current_user()
sets the current user by ID and username.
3. wp_set_auth_cookie()
sets the authentication cookies for the logged-in user.
4. The do_action( 'wp_login', $user->user_login )
action triggers the login action for WordPress.