Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 !

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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

share|improve this answer
    
Thank you for your help :-) ! –  user54952 Jul 22 at 9:35

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

share|improve this answer
    
Thank you for your help ! –  user54952 Jul 22 at 9:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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