I’m hooking auth_redirect
to wp_head
, but it’s returning cannot modify header information. Do I have to hook it to a different action? Something that loads before wp_head? I tried hooking it to get_headers and send_headers, but then it didn’t even work.
Any ideas? Thanks!
add_action('wp_head','check_if_logged_in');
function check_if_logged_in() {
$pageid = get_option('sd_page_id');
if ( !is_user_logged_in() && is_page($pageid) ) {
auth_redirect();
}
}
Also, to clarify, for some reason it works in localhost but not on my server. Weird.
It works fine on my localhost as well.
The reason it probably doesn’t work on your server is that it’s not using output buffering. Hooking into
wp_head
means that the page has already started printing to the client’s screen. Meaningauth_redirect
‘s use ofwp_redirect
will fail: the headers have already been sent and you see the “headers already sent” error.Try hooking into
template_redirect
instead ofwp_head
. I wouldn’t useauth_redirect
here either. You’re already checking if the user is logged in (whichauth_redirect
does as well). Simply sent users to the login page with an appropriate “redirect_to” argument if they aren’t logged in.