Here is the final code to get sessions to write to the usermeta and delete on logout. This code works with WordPress 4.5.2. The code is for user_id information only.
add_action( 'after_setup_theme', 'new_login' );
function new_login() {
$user_id = ''; // Change your code to grab user_id from external source
if ( $user_id > 0 && ! is_user_logged_in() ) {
$user = get_user_by( 'id', $user_id );
wp_clear_auth_cookie();
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID, true, is_ssl() );
if ( is_user_logged_in() ) {
return true;
}
} elseif ( $user_id == 0 && is_user_logged_in() ) {
wp_logout();
wp_set_current_user( 0 );
}
}
There are a couple of key issues. First, the conditional ! is_user_logged_in()
must be included with the check for a user_id
greater than zero. Next, the wp_set_current_user(0)
must follow the wp_logout()
in order to avoid a refresh.
I hope this helps others trying to get external authentication working with user_id information only.