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. Meaning auth_redirect
‘s use of wp_redirect
will fail: the headers have already been sent and you see the “headers already sent” error.
Try hooking into template_redirect
instead of wp_head
. I wouldn’t use auth_redirect
here either. You’re already checking if the user is logged in (which auth_redirect
does as well). Simply sent users to the login page with an appropriate “redirect_to” argument if they aren’t logged in.
<?php
add_action('template_redirect','wpse64899_check_if_logged_in');
function wpse64899_check_if_logged_in()
{
$pageid = 2; // or whatever you want it to be
if(!is_user_logged_in() && is_page($pageid))
{
$url = add_query_arg(
'redirect_to',
get_permalink($pagid),
site_url('wp-login.php')
);
wp_redirect($url);
exit;
}
}