Redirect visitors to new domain, unless logged in. WordPress.

So – here is a very interesting piece of code, that I wanted to share.

One customer came to me with a problem – company decided to move to a new domain and they wanted to redirect everyone, but keep it separately. So – new domain would be on new hosting, totally separate and visitors from old should be redirected to it. But for some reason – they also wanted to have an option to login to the old site. Basically – redirect if not logged in, let login and do not redirect, if logged in.

I have googled a bit and cooked up the following code, that I put into functions.php of the active theme on the old site (remember, we have 2 totally separate WordPress installations here).

add_action( 'init', 'redirect_non_logged_users_to_specific_page' );
function redirect_non_logged_users_to_specific_page() {
  if ( !is_user_logged_in() && $GLOBALS['pagenow'] !== 'wp-login.php' && $_SERVER['PHP_SELF'] != '/wp-admin/admin-ajax.php' ) {
   wp_redirect( 'https://hlyja.is'.$_SERVER["SCRIPT_URL"] ); 
   exit;
  }
}

And it worked like a charm! 🙂

Facebooktwitterredditpinterestlinkedinmail