限制WordPress 部分用户角色访问后台
- 时间:1年前
- 浏览:208次
有时我们想限制wordpress/" target="_blank" style="margin: 0px; padding: 0px; color: rgb(61, 167, 13); text-decoration-line: none !important;">WordPress 部分用户角色访问后台,可以通过下面的代码实现。
一、只允许管理员、编辑和作者角色访问后台
将下面代码添加到当前主题函数模板functions.php中:
1 2 3 4 5 6 7add_action(
'init'
,
'zm_redirect_wp_admin'
);
function
zm_redirect_wp_admin() {
if
( is_admin() && is_user_logged_in() && !current_user_can(
'manage_options'
) && !current_user_can(
'publish_pages'
) && !current_user_can(
'publish_posts'
) && ( !defined(
'DOING_AJAX'
) || !DOING_AJAX ) ){
wp_safe_redirect( home_url() );
exit
;
}
}
判断是否登录及用户角色,禁止访问后台的用户角色直接跳转到网站首页。
如果需要跳转到指定的页面链接,比如前端用户中心,可以将第4行的代码修改为类似:
1wp_safe_redirect(
'https://zmingcx.com/'
);
只能跳转到站内链接,不能转到站外链接。
如果只允许管理员访问后台,可将其中允许编辑和作者进入后台的代码删除:
1&& !current_user_can(
'publish_pages'
) && !current_user_can(
'publish_posts'
)
二、禁止默认注册用户角色进入后台
默认注册用户角色指的是:WordPress后台 → 设置 → 常规,设置新用户默认角色中的角色。
1 2 3 4 5 6 7if
( is_admin() && ( !defined(
'DOING_AJAX'
) || !DOING_AJAX ) ) {
$current_user
= wp_get_current_user();
if
(
$current_user
->roles[0] == get_option(
'default_role'
)) {
wp_safe_redirect( home_url() );
exit
();
}
}
如果你修改了新用户默认角色,对之前已注册的其他角色的用户将无效。
上述两段代码都加了判断,不会影响前端ajax请求。