0

Is there a way to redirect users returning to the site who are already logged in? Assuming something like:

function returning_redirect()
{
   //code here
}

add_action('auth_cookie_valid', 'returning_redirect');

But I can't seem to get any variation of that to work. Thanks!

  • 1
    Your initial idea will work but you are going to trap users in a redirect. What criteria determines "returning" vs "not returning, just been here a long time"? – s_ha_dum Dec 2 '13 at 2:18
  • Basically, I'm looking to redirect anyone who has previously signed in and still remains signed in (using the "remember me" cookie) but, I want this redirect to happen only when they return to my site from some other site. Still possible? Is the 'auth_cookie_valid' the correct acton hook? Thanks! – GuyLearningWordpress Dec 2 '13 at 13:29
1
function redirect_user() {    
        if ( is_user_logged_in() ) {
           wp_redirect( 'http://yoursite.com/page/' );
           exit;
        }
}
add_action( 'init', 'redirect_user' );

This will redirect the user to the page of your choice if they are logged in. It might be necessary to add a conditional that checks to make sure the user isn't already on that page, to avoid a continuous redirect loop.

  • This will trap a logged in user on that one single page. – s_ha_dum Dec 2 '13 at 2:15
0

A bit crude but...

function returning_redirect($a) {
  remove_action('auth_cookie_valid', 'returning_redirect');
  if (is_user_logged_in()) {
    if (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_HOST) !== parse_url(site_url(), PHP_URL_HOST)) {
        wp_redirect(site_url('page'));
        exit;
    }
  }
  add_action('auth_cookie_valid', 'returning_redirect');
}
add_action('auth_cookie_valid', 'returning_redirect');

You are checking the HTTP_REQUEST header for a match against the server host name.

Caveats:

  • That will not work on a server with multiple sub-directory installs like http://site.com/wordpress and http://site.com/wordpress2 because that will only check the site.com part. If that is your circumstance you will need something more complicated.
  • $_SERVER['HTTP_REFERER'] is easily spoofed, but if there are no security issues that should be no problem.
  • I expect that this is is going to be an annoying feature of your site.

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.