3

I am trying to programmatically log in a wordpress user, using the following function for that.

    public function auto_login( $user ) {
        $username = $user;
            if ( !is_user_logged_in() ) {
            $user = get_user_by( 'login', $username );
                wp_set_current_user( $user->ID, $user->user_login );
                wp_set_auth_cookie( $user->ID );
                do_action( 'wp_login', $user->user_login );
            }     
}

Unfortunately it seems not to be working. That function is called from within a shortcode. Could this be the explanation ? Should I rather hook my function to some filter, before any content is output ? Also I would like to redirect the newly logged in user to a specific post based on a $_GET parameter, can I simply add a header redirect at the end of the function ?

Thank you in advance for your help !

2 Answers 2

1

Do this on template_redirect hook. You can use wp_safe_redirect to redirect to different page in the blog. I can't give you the code because I don't from where you are getting the $user

0
5

You can try this function as it is working for me

function custom_login() {
    $creds = array();
    $creds['user_login'] = 'example';
    $creds['user_password'] = 'plaintextpw';
    $creds['remember'] = true;
    $user = wp_signon( $creds, false );
    if ( is_wp_error($user) )
        echo $user->get_error_message();
}
// run it before the headers and cookies are sent
add_action( 'after_setup_theme', 'custom_login' );

For details please visit the official site here

1
  • this is great answer. but what is remember. remember login info for next login? Commented Dec 17, 2018 at 6:55

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.