使用PAGE_TEMPLATE筛选器在用户未登录时更改模板(不起作用)

时间:2014-04-02 作者:dlopezgonzalez

我想在用户未登录时打印其他模板。我使用此代码:

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 );
我在我的子主题文件夹中有一个名为“need login.php”的模板文件,然而,我的网页在屏幕上打印了一个很大的空白。

我做了什么坏事?

当做

1 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

您的代码实际上没有任何作用”;“用户已登录”;检查一下,您不会使用global您导入的。

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 );
您可以通过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 );
如果你得到一个白色的屏幕几乎可以肯定,因为你的路径是错误的,你没有debugging enabled. 尝试:

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 );
这应该告诉你,你的道路是否正确。

如果是,请检查您的.php 文件,并确保服务器可读。

结束

相关推荐

Custom Post Templates

The Issue: 我正在寻找定制的单篇文章模板,以添加或删除单个元素作为普通单篇文章的功能。有很多方法可以在WordPress中为单个帖子创建自定义帖子模板。尤其是post格式是使用默认模板处理默认情况的绝佳机会;然而,我需要真正的自定义模板。The Idea: 我的第一种方法是根据post ID添加if/else语句:// check if custom post if ( is_single(\'999\') ) // check if there is a custom