如何对WordPress特定用户角色隐藏后台管理通知

当你在 WordPress 管理后台界面时,你会遇到一些“管理通知(Admin Notices)”,让你知道错误、更新设置、请求操作等等。

这些通知一般是WordPress内核、主题和插件添加的,倡萌之前分享过《如何为 WordPress 主题和插件添加管理通知(Admin Notices)》,如果你是开发者,可以看一下。今天我们要分享的内容是:如何对WordPress特定用户角色隐藏后台管理通知

为什么要对特定角色隐藏呢?举个最简单但是很常用的例子:你网站后台有一些非管理员的用户可以访问,但是很多后台的通知信息对他们来说都是多余的。这时候你就可以将这些信息对他们进行屏蔽。

实现的方法很简单,将下面的代码添加到主题的 functions.php 文件即可:

/**
 * 对非管理员角色隐藏后台通知
 * https://www.wpdaxue.com/hide-admin-notices-for-a-specific-role-in-wordpress.html
 */
function wpkj_hide_notices(){
    if (!current_user_can('manage_options')) { //如果你要定义其他角色,需要修改这行的条件 
        remove_all_actions( 'admin_notices' );
    }
}
add_action( 'admin_head', 'wpkj_hide_notices', 10 );

现在我们来看下逻辑:

  1. 先创建了一个名为 wpkj_hide_notices 的函数,然后挂载到 admin_head 这个钩子,使函数生效。
  2. 在函数内部,我们使用了一个判断条件 current_user_can('manage_options') ,意思是如果当前用户可以 manage_options ,那就是管理员角色,然后我们在前面添加了一个感叹号 ! ,就使条件反过来了,如果当前用户不可以 manage_options ,那就是非管理员角色了。
  3. 判断了如果当前用户不是管理员角色,就执行 remove_all_actions( 'admin_notices' ) ,也就是用这个函数移除了所有后台通知。

这里面涉及到的知识点:

  1. admin_head 钩子
  2. current_user_can() 函数 及 用户角色能力
  3. admin_notices 钩子 和 remove_all_actions() 函数

来源:

https://www.wpdaxue.com/hide-admin-notices-for-a-specific-role-in-wordpress.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32366.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?