CMS WordPress

Programmatically Sign-on a WordPress User, the true way!

function rsf_programmatic_login( $username ) {

    if ( is_user_logged_in() ) {
        wp_logout();
    }

    add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );	// hook in earlier than other callbacks to short-circuit them
    $user = wp_signon( array( 'user_login' => $username ) );
    remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );

    if ( is_a( $user, 'WP_User' ) ) {
        wp_set_current_user( $user->ID, $user->user_login );

        if ( is_user_logged_in() ) {
            return $user;
        }
    }
    return false;
}

function rsf_allow_programmatic_login( $user, $username, $password ) {
    return get_user_by( 'login', $username );
}

Leave a Reply

Your email address will not be published. Required fields are marked *