指定 wordpress 默认用户角色后台登陆权限
- 时间:2020-05-17 12:16:18
- 分类:网络文摘
- 阅读:155 次
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
推荐阅读:Why Social Media is Crucial to Your Marketing Efforts The Difference Between Gillette & Nike Ads Result-Driven Trends in 2019 to Get Backlinks from Quality Websi The Contiguous Binary Array with Equal Numbers of Ones and Zeros Microbit Programming: Showing a Running Pixel on the LED How to Print Immutable Linked List in Reverse using Recursion or The Most Useful Tools for Reverse Phone Lookup How to Solve the WIFI (Wireless Networks) Intermittency Issues? How to Reverse a Linked List in Javascript? Bash Function to Check if a Kubernetes Pod Name is Valid
- 评论列表
-
- 添加评论