WordPress:如何仅对同时拥有Editor和Contributor角色的用户隐藏Posts后台菜单
解决WordPress中仅移除同时拥有Editor和Contributor角色用户的后台Posts菜单问题
原代码的问题在于current_user_has_role函数处理角色数组时,只要用户拥有其中任一角色就返回true(逻辑“或”),而我们需要的是用户同时拥有所有指定角色(逻辑“且”)。
修改后的完整代码:
function hide_posts_in_admin_menu() : void { if ( ! function_exists( 'current_user_has_role' ) ) { function current_user_has_role( $role ) { $user = get_userdata( get_current_user_id() ); if ( ! $user || ! $user->roles ) { return false; } if ( is_array( $role ) ) { // 改为检查所有传入的角色都存在于用户角色列表中 $matched_roles = array_intersect( $role, (array) $user->roles ); return count( $matched_roles ) === count( $role ); } return in_array( $role, (array) $user->roles, true ); } } // 仅当用户同时拥有editor和contributor角色时,移除Posts菜单 if ( current_user_has_role( array( 'editor', 'contributor' ) ) ) { remove_menu_page( 'edit.php' ); } } // 记得添加钩子触发函数,比如: // add_action( 'admin_menu', 'hide_posts_in_admin_menu' );
关键修改说明:
- 角色判断逻辑调整:在
current_user_has_role的数组处理分支中,从“存在任一匹配角色即返回true”改为“所有传入角色都匹配才返回true”——通过比较交集数组的长度和传入角色数组的长度实现。 - 条件判断修正:原代码的反向判断逻辑改为正向判断,直接在用户同时拥有两个角色时执行菜单移除操作,逻辑更直观。
内容的提问来源于stack exchange,提问作者Beata
相关产品推荐
相关产品推荐

