I'd like to use links from my application to log users into Wordpress in their browser, but I'm concerned about whether this can be done securely.

Obviously using any sort of static URL pattern seems out of the question. Are there some other methods I can take advantage of to do this securely without spending a week building a custom mechanism?

I am guessing not, but before potentially re-inventing the wheel, I wanted to check. Thanks very much.

1 Answer 1


Yes, you can. However, you'll need to know either the userid or the username.

Create a link with any of that as a data attribute and make a ajax call with that. On success, you can just reload the page and your user will be logged in.

If you know the user id..

function wpse_304392_login_by_id() {

    $user_id = $_POST['user_id'];

    $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 );

    wp_die(); //Essential for AJAX calls

If you know the username..

function wpse_304392_login_by_username() {

    $username = $_POST['username'];
    $user = get_user_by( 'login', username ); 
    $user_id = $user->ID;

    if( $user ) {
        wp_set_current_user( $user_id, $username );
        wp_set_auth_cookie( $user_id );
        do_action( 'wp_login', $username );

    wp_die(); //Essential for AJAX calls

Don't forget do a nonce check to make it secure.

  • 1
    This is not secure, and adding a nonce check will not make it more secure. The user is not authenticated yet, so the nonce will be generic, and therefore useless. I could supply any user ID or username and log in as that user.
    – J.D.
    May 25, 2018 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.