0

I want to print other template when the user is not logged in. I use this code:

function restrict_access_to_unlogged_users($template) {
    global $post, $pagename;
    $new_template = get_stylesheet_directory() . '/need-login.php';
    return $new_template;
}
add_filter( 'page_template', 'restrict_access_to_unlogged_users', 20 );

I have got a template file called "need-login.php" in my child theme folder, however, my webpage prints a big blank in the screen.

What Am I doing bad?

Regards.

2

Your code doesn't really do any "user logged in" check, and you aren't using a couple of the globals you import.

function restrict_access_to_unlogged_users($template) {
  if (!is_user_logged_in()) {
    $template = get_stylesheet_directory() . '/need-login.php';
  }
  return $template;
}
add_filter( 'page_template', 'restrict_access_to_unlogged_users', 20 );

And you could do this more globally with template_include.

function restrict_access_to_unlogged_users($template) {
  if (!is_user_logged_in()) {
    $template = get_stylesheet_directory() . '/need-login.php';
  }
  return $template;
}
add_filter( 'template_include', 'restrict_access_to_unlogged_users', 20 );

If you are getting a white screen is almost certainly because your path is wrong and you do not have debugging enabled. Try:

function restrict_access_to_unlogged_users($template) {
  if (!is_user_logged_in()) {
    $template = get_stylesheet_directory() . '/need-login.php';
  }
  var_dump($template);
  die;
}
add_filter( 'page_template', 'restrict_access_to_unlogged_users', 20 );

That should tell you if you've got the path right.

If you do, check the permissions on your .php file and make sure it is readable by the server.

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.