-1

I have created a page with a custom login using wp_login_form() function but how can I redirect all visitors to that page in similar way described in that topic?

My code looks like:

function redirect_to_login_if_guest() {

global $post;

if ( ! is_admin() && ! is_user_logged_in() && $post->ID !== 4667 ) {
    wp_redirect( get_permalink(4667) );
    exit;
}
}
add_action( 'wp_loaded', 'redirect_to_login_if_guest' );

but somehow is going into infinite loop instead of a login page. It looks like wp_loaded can't be used in my case.

Similar code moved to the `header.php'

global $post;

if ( ! is_admin() && ! is_user_logged_in() && $post->ID != 4667 ) {
    wp_redirect( get_permalink(4667) );
    exit;
}

works flawless so still it points on triggering action on wp_loaded. Any thoughts?

  • How about trying it yourself? – kaiser Mar 16 '15 at 19:39
  • My question contains that part too - just need directions or idea how to handle that kind of functionality. I don't need copy-paste code - that part I can do on my own. – JackTheKnife Mar 16 '15 at 19:52
  • 2
    What about checking that you are not in page 4667 before redirect to it again? It is simple. – cybmeta Mar 16 '15 at 21:31
  • 1
    Jack, please do not destroy questions just because someone pointed out that you could just try something when asking. The part wasn't there when you asked - see the revision history. Next thing, please take a look at the comments by @ialocin and cybmeta: You have an endless loop because you are redirecting to the same page even if you are already on it. How are you attempting to fix that? – kaiser Mar 16 '15 at 22:22
  • 1
    F** it, you tried to make your question better, so I'm trying to help, see my answer. – Nicolai Mar 17 '15 at 14:34
1

In short, the $post global isn't setup at the wp_loaded state. See:

for detailed information.

So use another hook, like template_redirect.

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.