Log in a WordPress user programmatically
With this snippet you can log in a WordPress user automatically.
<?php
function auto_login( $user ) {
$username = $user;
// log in automatically
if ( !is_user_logged_in() ) {
$user = get_userdatabylogin( $username );
$user_id = $user->ID;
wp_set_current_user( $user_id, $user_login );
wp_set_auth_cookie( $user_id );
do_action( 'wp_login', $user_login );
}
}
?>
This isn't a better or alternative method. But use it if you're trying to get the above code to work after headers have been output and you're not trying to redirect the user.