有时我们想限制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( 'https://zmingcx.com/' );登录后复制
如果只允许管理员访问后台,可将其中允许编辑和作者进入后台的代码删除:
&& !current_user_can('publish_PAges') && !current_user_can('publish_posts')登录后复制
默认注册用户角色指的是:Wordpress后台 → 设置 → 常规,设置新用户默认角色中的角色。
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(); } }登录后复制
代码出自:www.ludou.org
如果你修改了新用户默认角色,对之前已注册的其他角色的用户将无效。
上述两段代码都加了判断,不会影响前端ajax请求。
相关推荐:《WordPress》