指定 wordpress 默认用户角色后台登陆权限

  • 时间:2020-05-17 12:16:18
  • 分类:网络文摘
  • 阅读:144 次

wordpress 默认的用户角色有五种:管理员、编辑、作者、投稿者、订阅者。对于开放注册的 wordpress 而言,用户注册后可以通过访问 wordpress 后台地址进入仪表盘,显然这不是我们想要的效果,可以通过以下代码来限制 wordpress 部分用户角色访问后台。

一、只允许管理员、编辑和作者角色访问后台

将下面代码添加到当前 wordpress主题函数模板 functions.php 中:

  1. add_action( 'init', 'zm_redirect_wp_admin' );
  2. function zm_redirect_wp_admin() {
  3.     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 )  ){
  4.         wp_safe_redirect( home_url() );
  5.         exit;
  6.     }
  7. }

上述代码将判断用户角色及是否登录,对于禁止访问后台的用户角色会直接跳转到网站首页。

如果需要跳转到指定页面(只能设置跳转到站内链接),比如前端用户中心,可将第4行的代码修改为类似:

  1. wp_safe_redirect( 'http://uuxn.com/' );

如果只允许管理员访问后台,可将其中允许编辑和作者进入后台的代码删除:

  1. && !current_user_can('publish_pages') && !current_user_can('publish_posts')

二、禁止默认注册用户角色进入后台

添加如下代码到当前 wordpress主题函数模板 functions.php 中:

  1. if ( is_admin() && ( !defined( 'DOING_AJAX' ) || !DOING_AJAX ) ) {
  2.     $current_user = wp_get_current_user();
  3.     if($current_user->roles[0] == get_option('default_role')) {
  4.         wp_safe_redirect( home_url() );
  5.     exit();
  6.     }
  7. }

默认注册用户角色指:WordPress后台 → 设置 → 常规,设置“新用户默认角色”中的角色。

wordpress 新用户默认角色

如果你以前有过修改 wordpress 新用户默认角色,则对代码布署之前已注册的其他角色用户无效。

注:上述两段代码已加判断,不会影响前端ajax请求。

原文:https://zmingcx.com/wordpress-redirect-wp-admin.html

推荐阅读:
Did You Know There Are Some Great Scientific Reasons to Use Emot  5 Simple Tips for Creating More Irresistible Product Pages  You Should Know These Facts About Instagram  Why Bloggers Need to Understand Google Rankbrain  How to Write Compelling Blog Content for Boring Niches  Why Curvy Blogger Put On A Bikini For The First Time In 25 Years  Blogger Gives His Secret To Becoming A Millionaire By Age 30  One Food Blog Is Proving Just How Successful Food Blogs Can Be  Planning To Update Your Website For 2020? Read This.  Learn to Stay Cool in Online Casinos and Control Emotions 
评论列表
添加评论