#更新:哇,我觉得自己像个小丑。。。哈哈。WP_Role::has_cap
我的眼睛不够硬。
$caps = array( \'cap_1\', \'cap_2\', \'cap_3\' );
$roles = array( \'administrator\', \'editor\' );
foreach( $roles as $role ) {
if( $role_object = get_role( $role ) ) {
foreach( $caps as $cap ) {
if( !$role_object->has_cap( $cap ) ) {
$role_object->add_cap( $cap );
}
}
}
}
忽略这一点:很抱歉,我的另一个答案是每个用户,而不是每个角色。
您可以做的是检查角色是否具有使用get_role()
你可以看到get_role( \'administrator\' )
将返回一个包含一系列功能的对象。
$administrator = get_role( \'administrator\' );
// Make sure role object was retrieved
if( $administrator ){
//See if it\'s got our capability or not
if( !in_array( \'my-custom-cap\', $administrator->capabilities ) ){
// Wasn\'t there, so add it here
$administrator->add_cap( \'my-custom-cap\' );
}
}
如果出于某种原因,您不想运行
$role
每次进行对象比较时,可以定义一次,然后在数据库中使用
update_option()
并检查
get_option()
if( get_option( \'manually_set_add_cap_admin\' ) != true ){
$administrator = get_role( \'administrator\' );
// Make sure role object was retrieved
if( $administrator ){
//See if it\'s got our capability or not
if( !in_array( \'my-custom-cap\', $administrator->capabilities ) ){
// Wasn\'t there, so add it here
$administrator->add_cap( \'my-custom-cap\' );
update_option( \'manually_set_add_cap_admin\', true );
}
}
}
这里有一个更冗长的解决方案,它将遍历您添加的任何角色,并为它们提供所有适当的功能。循环完成后,它将设置一个选中的标志,这样在第一次运行之后就不会有任何WP\\U角色对象获取。
// Define flag as a variable to prevent typos, in update/get_option
// or it will constantly run (I know from experience...)
$flag = \'manually_added_my_custom_caps\';
if( !get_option( $flag ) ){
// Our flag option wasn\'t set, that means this code hasn\'t run yet.
$roles = array( \'administrator\', \'editor\' );
$capabilities = array( \'custom-cap-1\', \'custom-cap-2\' );
// Loop through each role
foreach( $roles as $role ){
// Make sure we got a WP_Role object back
if( $role_object = get_role( $role ) ){
// Loop through our custom capabilities
foreach( $capabilities as $cap ){
// Our option flag wasn\'t set, but let\'s confirm
// that the role doesn\'t have the cap
if( !in_array( $cap, $role_object->capabilities ) ){
// Confirmed not there, add it here
$role_object->add_cap( $cap );
}
}
}
}
// Our function ran, it should have set all caps to all the roles
// so now our code will skip this entirely next time
update_option( $flag, true );
}