2

I've tried this to redirect people who aren't logged in to certain page. It ultimately shouldn't matter what front end page they visit, but should redirect to whatever page is chosen as the landing page (which I'm assuming would be the URL in the wp_redirect). I still need access to wp-login and dashboard etc...

I placed the following code in my functions.php, but did not work.

function my_redirect() {    
   if ( $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] == 'mybigfatsite.com/' ) {
    if ( ! is_user_logged_in() ) {
       wp_redirect( 'mybigfatsite.com/landing/' );
       exit;
    }
}
}
add_action( 'init', 'my_redirect' );

Thanks for any help!

  • 1
    HTTP_HOST typically doesn't contain http://, do some debugging to figure out what you're actually trying to match. – Milo Aug 15 '14 at 19:52
  • Thanks Milo. Perhaps my question - or my knowledge! - isn't clear, I'm pretty "green". I did remove the http:// from the above code and the home page redirects to the landing page, but I'd like all pages to redirect to the landing page. I'm not sure how to do this. – alexwc_ Aug 15 '14 at 20:01
8

The is_login_page() function is taken from here

function is_login_page() {
    if ( $GLOBALS['pagenow'] === 'wp-login.php' && ! empty( $_REQUEST['action'] ) && $_REQUEST['action'] === 'register' )
        return true;
    return false;
}

function my_redirect() {  
    //if you have the page id of landing. I would tell you to use if( is_page('page id here') instead
    //Don't redirect if user is logged in or user is trying to sign up or sign in
    if( !is_login_page() && !is_admin() && !is_user_logged_in()){
        //$page_id is the page id of landing page
        if( !is_page($page_id) ){
            wp_redirect( get_permalink($page_id) );
            exit;
        }
    }
}
add_action( 'template_redirect', 'my_redirect' );
  • this gives me the following: In Chrome "This page has a redirect loop" and in Safari "Too many redirects occurring..." – alexwc_ Aug 15 '14 at 20:18
  • @leftside Stupid mistake on my part. Try it now. – sakibmoon Aug 15 '14 at 20:20
  • thanks sakiboom. I kept getting redirects, but I changed your code to wp_redirect('/landing'); and now it sort of works - except I still need access to the login page and admin area. I've edited my question. – alexwc_ Aug 15 '14 at 20:26
  • @leftside It should work now. – sakibmoon Aug 15 '14 at 20:46
  • 1
    @leftside updated just now. Be sure to use is_page() rather than SERVER variables. It will save you from tons of problem later. – sakibmoon Aug 16 '14 at 1:32

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.