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 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);
      wp_set_auth_cookie($user->ID);
      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;
      }
      wp_redirect($final_url);
      exit;
      }
    } 

  }
} 
share|improve this question

1 Answer 1

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.

Example:

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

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.