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;


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);
| improve this answer | |

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.