WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to auto-login visitors to WP through email links. I use a "userid" parameter with their email and a "redirect_to" one to know where to point them. There are some protected areas in the site, just for registered visitors, and they can't see them if they don't log in first (that's the reason of the auto-login).

My problem is that the auto-login works fine, but only the second time someone follows the link. Otherwise, they get a message saying that page is protected. Should I try another hook?

This is my code:

class zelfunctions

  public function __construct()
    add_action( 'init', array(&$this, "autologin"));

  public function autologin(){
   if (!is_user_logged_in()) {

    $redirect = isset($_GET['redirect_to']) ? esc_attr($_GET['redirect_to']) : false; 
    $useremail = isset($_GET['userid']) ? sanitize_user($_GET['userid']) : false;
    if ($user = get_user_by( 'email', $userid )) {
      wp_set_current_user($user->ID, $user->user_login);
      do_action('wp_login', $user->user_login);
      if (!$redirect) {
      //If there isn't any redirect set, just redirect to the home (already logged in)
         $final_url = home_url('/');
      } else {
         $final_url = home_url('/'). $redirect;

share|improve this question
up vote 1 down vote accepted

The init hook is too early, so the is_user_logged_in() check is failing.

Try using the wp_head hook instead (with a -1 priority). The exit/die function will still prevent the page from loading, but will give you more access to key globals you may need to evaluate.


add_action( 'wp_head', array(&$this, "autologin"), -1);
share|improve this answer

Your Answer


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.