0

I have a simple auto log in hook that looks like the following:

function auto_login() {
    if (!is_user_logged_in()) {
        //Removed some code for brevity.

        $user = get_userdatabylogin($domainName);

        if ($user != null) {
            //Set the auth cookie.
            wp_set_auth_cookie($user->ID, false, null);
            //Set the current user (this will also set WP objects at the global level)
            wp_set_current_user($user->ID);
        }
    }
}
add_action('init', 'auto_login');

This code does work, but, in order to get the admin bar at the top of the page it requires a page refresh. This makes me think that I'm not getting some global objects populated early enough in the Wordpress page life cycle.

Should I be calling this method somewhere else besides init?

2 Answers 2

2

Maybe it is too late to hook on init. Try set_current_user or some earlier hook. List is here: https://codex.wordpress.org/Plugin_API/Action_Reference

1
  • Cheers. It looks like set_current_user is early enough in the cycle to accomplish this. Feb 1, 2013 at 14:56
0

I've found that the user can be automatically logged in on template_redirect and set successfully using wp_redirect('yoururl'), which, essentially, redirects back with the cookie instead of reloading the page.

Example:

function auto_login() {
    // if statements go here...

    $user_id = 'some_user_id';

    wp_set_auth_cookie($user_id);
    wp_set_current_user($user_id);

    wp_redirect(home_url());
    exit;
}
add_action('template_redirect', 'auto_login');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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