第一个问题是如何识别页面是否是受限页面之一。
如果页面只有一个,您可以从我这里对其进行硬编码(即,自己写ID或slug),这并不好,但一个页面可以接受。如果页面不止一个,您可能需要找到不同的解决方案。
我建议创建一个名为“Restricted page”的页面模板,并将其分配给所有要限制的页面。
所以创建一个名为page-restriced.php
, 将其保存在您的主题根目录中,并在其中编写如下内容:
<?php
/**
* Template Name: Restricted Page
*/
?>
<?php get_template_part(\'page\'); ?>
现在,将“受限页面”模板分配给所有要重新限制的页面。
如果一个不允许的用户试图访问一个受限制的页面,您不会说要做什么。
一种解决方案是将页面的内容挂接到the_content
过滤器:
add_filter(\'the_content\', \'change_content_by_role\');
function change_content_by_role( $content ) {
remove_filter(\'the_content\', \'change_content_by_role\');
if ( is_page_template(\'page-restriced.php\') ) {
// I suggest to allow access to administrator or probably you cannot access
$allowed_roles = array(\'administrator\', \'your_special_role\');
$the_user = wp_get_current_user();
if ( empty( array_intersect($allowed_roles, $the_user->roles ) ) ) {
return __(\'You are not allowed to view this page.\');
}
}
return $content ;
}
这个解决方案很不错,但在某些特定情况下可能会带来问题:如果页面中有一个在主查询之前运行的辅助查询。
另一个无问题的解决方案是创建一个名为“不允许”的文件。php’并将其放在主题文件夹中,挂接到template_include
如果不允许用户,则筛选并显示该文件。
add_filter(\'template_include\', \'restrict_page_by_role\');
function restrict_page_by_role( $template ) {
if ( is_page_template(\'page-restriced.php\') ) {
// I suggest to allow access to administrator or probably you cannot access
$allowed_roles = array(\'administrator\', \'your_special_role\');
$the_user = wp_get_current_user();
if ( empty( array_intersect($allowed_roles, $the_user->roles ) ) ) {
return get_stylesheet_directory() . \'/not-allowed.php\';
}
}
return $template;
}