如何仅向具有某些功能的用户显示管理条菜单项?
-
22-10-2019 - |
题
我正在尝试将项目添加到管理栏中,但仅适用于具有某些功能的用户,例如 add_movies
在插件中。问题是,根据 @toscho 和 @thedeadmedic, ,该插件在运行顺序中过早执行代码 current_user_can
.
我尝试使用 if ($user->has_cap('add_movies'))
但是得到 Fatal error: Call to a member function has_cap() on a non-object in xxx.
我是否缺少明显的全球,还是解决方案更复杂?
解决方案
如果您只在插件文件中写入该检查,则会过早调用该检查:
if ( current_user_can( 'add_movies' ) ) {
add_action( 'admin_bar_menu', 'wpse17689_admin_bar_menu' );
}
function wpse17689_admin_bar_menu( &$wp_admin_bar )
{
$wp_admin_bar->add_menu( /* ... */ );
}
因为它将在加载插件时执行,这是在启动过程中很早就执行的。
您应该做的是始终添加操作,然后在回调中进行操作检查 current_user_can()
. 。如果您无法执行操作,只需返回而不添加菜单项即可。
add_action( 'admin_bar_menu', 'wpse17689_admin_bar_menu' );
function wpse17689_admin_bar_menu( &$wp_admin_bar )
{
if ( ! current_user_can( 'add_movies' ) ) {
return;
}
$wp_admin_bar->add_menu( /* ... */ );
}
其他提示
尝试一下 if ( current_user_can('capability') ) : /* your code */; endif;
编辑:还没有完全阅读您的Q。您尝试过以下内容吗?
global $current_user;
get_currentuserinfo();
// Here you can start interacting with everything the current user has:
echo '<pre>';
print_r($current_user); // show what we got to offer
echo '</pre>';
// Then you'll have to do something with the role to get the caps and match against them