2

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.

2
  • Could you post the exact function that you are using to hook auth_redirect? Commented Sep 12, 2012 at 4:15
  • Ok added code in my original post
    – zen
    Commented Sep 12, 2012 at 21:53

1 Answer 1

5

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;
    }
}
4
  • Aha! That solved it. Is there a reason why you wouldn't use auth_redirect though? Just curious. Thanks!
    – zen
    Commented Sep 12, 2012 at 22:57
  • 1
    auth_redirect does the user logged in checking for you as well. If you're going to use it, there's no need to check of the user is logged in first. if(is_page($your_page)) { auth_redirect(); } It's also a pluggable function. Commented Sep 12, 2012 at 23:24
  • Oh ok I see. Got it!
    – zen
    Commented Sep 13, 2012 at 0:03
  • @chrisguitarguy thanks a lot for the explanation. Just learned the template_redirect thing in WordPress, and learned why wp_redirect() was showing "headers already sent". Thanks a lot for the explanation. Commented Apr 16, 2015 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.