指定 wordpress 默认用户角色后台登陆权限
- 时间:2020-05-17 12:16:18
- 分类:网络文摘
- 阅读:114 次
wordpress 默认的用户角色有五种:管理员、编辑、作者、投稿者、订阅者。对于开放注册的 wordpress 而言,用户注册后可以通过访问 wordpress 后台地址进入仪表盘,显然这不是我们想要的效果,可以通过以下代码来限制 wordpress 部分用户角色访问后台。
一、只允许管理员、编辑和作者角色访问后台
将下面代码添加到当前 wordpress主题函数模板 functions.php 中:
- add_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行的代码修改为类似:
- wp_safe_redirect( 'http://uuxn.com/' );
如果只允许管理员访问后台,可将其中允许编辑和作者进入后台的代码删除:
- && !current_user_can('publish_pages') && !current_user_can('publish_posts')
二、禁止默认注册用户角色进入后台
添加如下代码到当前 wordpress主题函数模板 functions.php 中:
- if ( 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();
- }
- }
默认注册用户角色指:WordPress后台 → 设置 → 常规,设置“新用户默认角色”中的角色。

如果你以前有过修改 wordpress 新用户默认角色,则对代码布署之前已注册的其他角色用户无效。
注:上述两段代码已加判断,不会影响前端ajax请求。
原文:https://zmingcx.com/wordpress-redirect-wp-admin.html
推荐阅读:How to Construct Minimum Spanning Tree using Kruskal or Breadth Two Pointer and Sliding Window Algorithm to Find K-Length Substr How to Get the Maximum Level Sum of a Binary Tree using Breadth Compute the Minimum Costs to Connect the Sticks using Priority Q Single-Row Keyboard Algorithms to Estimate the Finger Moving Tim Bruteforce Algorithm to Find the Next Closet Time Reusing the Cu The Overlapping Rectangles using CSS and Javascript How to Count the Distinct Pairs using HashMap? Blogger Jailed For Pokemon Go Gets Even More Trouble Dead Simple Ways to Keep Your Best Blogging Ideas From Slipping
- 评论列表
-
- 添加评论