根据用户角色限制前端访问,否则重定向到登录表单

时间:2018-01-11 作者:user13286

我在函数中创建了自定义用户角色。php文件。我正在为我的网站上的一个页面创建一个新的页面模板,我希望按角色(而不是按功能)限制该页面。基本上,我希望这样做,如果具有此新角色或任何编辑/管理员角色的用户访问页面,他们将看到内容,否则将显示默认的Wordpress登录表单。我还希望它在登录后将它们发送回这个特定页面。这是我目前使用的代码,除了重定向不起作用外,它似乎大部分都在工作。我还尝试使用wp_login_form() 代替重定向,但它显示的是一个未设置样式的表单,而不是通过访问wp-login:

<?php
/*
 * Template Name: Restricted content
 * Description: Restricted content template
 */

get_header(); ?>

<?php if( current_user_can(\'custom-role\') || current_user_can(\'administrator\') || current_user_can(\'editor\')) { ?>

<div>
    Restricted content displayed here
</div>

<?php get_footer(); ?>

<?php

} else {
    wp_redirect(wp_login_url());
} 

?>

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

在您已经输出HTML之后,WP无法重定向-因此,在调用标题之前,将if/else移到顶部,并且只输出标题(&L);如果满足条件,请填写页脚。

另外,不使用current_user_can(\'role\'), 使用current_user_can(\'capability\') - i、 e。

<?php if(
    current_user_can(\'activate_plugins\') ||
    current_user_can(\'edit_a_defined_custom_post_type\')
) {
    get_header(); ?>
    <div>Restricted content here</div><?php
    get_footer();
} else {
    wp_redirect(wp_login_url());
} ?>
(根据Codex,“虽然部分支持检查替代能力的特定角色,但不鼓励这种做法,因为它可能会产生不可靠的结果。”)

结束

相关推荐

403 error on admin login page

我这里有个问题。我有一个wordpress站点,不小心将http更改为https,我不确定是否可以将其更改回来。什么是确定的,它让我注销了,当我重新加载管理员登录页面时,它抛出了一个错误,即我的连接不是私有的,然后我得到了一个403禁止页面。我有权访问FTP并尝试更改wp\\U配置文件,但未成功。已尝试添加此项:define(\'WP_HOME\',\'http://example.com\'); define(\'WP_SITEURL\',\'http://example.com\');