如何为WordPress作者角色设置Redirection插件的专属访问权限?
WordPress作者角色仅访问Redirection插件页面的解决方案
核心思路
不要直接移除manage_options权限(这会导致整个工具/设置栏目不可见),而是通过自定义权限+修改插件权限校验+隐藏多余菜单的组合方式,实现精准访问控制。
具体实现代码
将以下代码添加到主题的functions.php文件中:
1. 配置作者角色的基础权限
function add_theme_caps() { $role = get_role( 'author' ); // 保留你需要的编辑权限 $role->add_cap( 'edit_published_posts' ); $role->add_cap( 'edit_others_posts' ); $role->add_cap( 'edit_published_pages' ); $role->add_cap( 'edit_others_pages' ); // 添加Redirection专属的自定义权限 $role->add_cap( 'manage_redirection' ); } add_action( 'admin_init', 'add_theme_caps' );
2. 替换Redirection的权限校验规则
Redirection默认要求manage_options权限,我们将其替换为自定义的manage_redirection:
function custom_redirection_cap( $capability ) { return 'manage_redirection'; } add_filter( 'redirection_role', 'custom_redirection_cap' );
3. 隐藏工具菜单下的其他子项
只保留Redirection的入口,屏蔽工具栏目下的其他页面:
function hide_unwanted_tool_menu_items() { global $submenu; if ( isset( $submenu['tools.php'] ) ) { $allowed_submenus = array(); foreach ( $submenu['tools.php'] as $key => $item ) { // 匹配Redirection的菜单标题,若后台显示不同请自行修改 if ( $item[0] === 'Redirection' ) { $allowed_submenus[$key] = $item; } } $submenu['tools.php'] = $allowed_submenus; } } add_action( 'admin_menu', 'hide_unwanted_tool_menu_items', 999 );
4. 确保工具主菜单对作者可见
让拥有manage_redirection权限的作者能看到工具菜单:
function show_tools_menu_for_author() { global $menu; $role = get_role( 'author' ); if ( $role->has_cap( 'manage_redirection' ) ) { foreach ( $menu as $key => $item ) { if ( $item[2] === 'tools.php' ) { $menu[$key][1] = 'manage_redirection'; break; } } } } add_action( 'admin_menu', 'show_tools_menu_for_author' );
注意事项
- 如果Redirection在后台显示的菜单标题不是"Redirection",请修改第三步代码中的匹配文本。
- 所有代码需添加到当前启用主题的
functions.php文件,或者封装成自定义插件使用更安全。
内容的提问来源于stack exchange,提问作者Lahiru Madushan Koralage
相关产品推荐
相关产品推荐

