0

Trying to add an action to redirect based on if user is not logged in and is accessing certain post types. Problem is, during template_redirect, $post is NULL and other ones the headers seem to have already been sent so it won't redirect. What would be the appropriate action to use here?

add_action( 'template_redirect', 'mytheme_restrict_user_content' );
function mytheme_restrict_user_content(){
    if (!is_user_logged_in() ) {
        $restrict = false;
        $restricted_post_types = array('documentlibrary', 'events');
        if ( in_array( $post->post_type, $restricted_post_types ) ){
            $restrict = true;
        }
        if ($restrict){
            auth_redirect();
        }
    }
}

1 Answer 1

1
add_action( 'pre_get_posts', 'mytheme_restrict_user_content' );

function mytheme_restrict_user_content( $query ){
  $restricted_post_types = array('documentlibrary', 'events');
  if ( is_main_query() && is_singular($restricted_post_types) && ! is_user_logged_in() ) {
    $redirect = set_url_scheme('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    wp_redirect( wp_login_url($redirect, true) );
    exit();
  }
}

I don't use auth_redirect because that function check if the user is logged in, but we already know that user is not logged in.

6
  • I liked that auth_redirect handles forwarding user to the correct page after in a little bundle. with your code I get Warning: Cannot modify header information - headers already sent
    – Damon
    Commented Aug 19, 2013 at 19:15
  • Hi @Damon pre_get_posts is fired before template_redirect. So there is something in your installation that sent header too early. 100% problem is not my code. My code also forwarding user to the correct page after login, runs faster and is more compact than one you posted.
    – gmazzap
    Commented Aug 19, 2013 at 19:19
  • 1
    Also don't forget that rely on template_redirect you run the DB query. Relying on pre_get_posts DB query is not runned so it's much better for your scope.
    – gmazzap
    Commented Aug 19, 2013 at 19:25
  • Hm. Maybe this is Genesis framework shenanigans.
    – Damon
    Commented Aug 19, 2013 at 19:28
  • I put it back to template_redirect and it's working with your code now. danke
    – Damon
    Commented Aug 19, 2013 at 20:10

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.