You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制WordPress订阅者仅访问wp-admin的profile.php页面?

解决订阅者仅能访问个人资料页的完整方案

嘿,我来帮你搞定这个问题!你的现有代码已经实现了页面跳转的核心逻辑,但还没处理后台菜单的显示,所以订阅者依然能看到Dashboard选项。咱们来完善一下,分两步实现完全限制:

1. 完善页面跳转逻辑

你的原代码已经能把非个人资料页的请求跳转到个人资料,但可以稍微优化下,让逻辑更清晰明确,确保AJAX请求不受影响:

function redirected_admin() {
    // 排除AJAX请求,避免影响后台异步操作
    if (defined('DOING_AJAX') && DOING_AJAX) {
        return;
    }
    
    // 检查当前用户是否是订阅者(无编辑文章权限)且不在个人资料页
    if (!current_user_can('edit_posts') && $GLOBALS['pagenow'] !== 'profile.php') {
        wp_redirect(get_edit_user_link());
        exit;
    }
}
add_action('admin_init', 'redirected_admin');

2. 移除订阅者的后台菜单选项

接下来要把订阅者看不到的菜单全部移除,只保留个人资料入口:

function remove_subscriber_menu_items() {
    // 仅针对订阅者角色执行
    if (current_user_can('subscriber')) {
        // 移除所有默认菜单
        remove_menu_page('index.php'); // 仪表盘
        remove_menu_page('edit.php'); // 文章
        remove_menu_page('upload.php'); // 媒体库
        remove_menu_page('edit.php?post_type=page'); // 页面
        remove_menu_page('edit-comments.php'); // 评论
        remove_menu_page('themes.php'); // 外观
        remove_menu_page('plugins.php'); // 插件
        remove_menu_page('users.php'); // 用户
        remove_menu_page('tools.php'); // 工具
        remove_menu_page('options-general.php'); // 设置
        
        // 确保个人资料菜单保留(其实默认订阅者能看到,但保险起见)
        add_menu_page('个人资料', '个人资料', 'read', 'profile.php', '', '', 99);
    }
}
add_action('admin_menu', 'remove_subscriber_menu_items');

额外优化:隐藏顶部工具栏的多余选项

如果还想隐藏顶部Admin Bar里的多余入口,可以再加这段代码:

function remove_subscriber_admin_bar_items() {
    if (current_user_can('subscriber')) {
        global $wp_admin_bar;
        // 移除不需要的工具栏节点
        $wp_admin_bar->remove_node('site-name');
        $wp_admin_bar->remove_node('dashboard');
        $wp_admin_bar->remove_node('new-content');
        $wp_admin_bar->remove_node('comments');
        // 保留个人资料节点
        $wp_admin_bar->add_node(array(
            'id' => 'my-profile',
            'title' => '我的资料',
            'href' => admin_url('profile.php')
        ));
    }
}
add_action('wp_before_admin_bar_render', 'remove_subscriber_admin_bar_items');

把这三段代码加到你的主题functions.php文件里,就能实现完全限制订阅者仅访问个人资料页,同时看不到其他后台菜单和工具栏选项啦!

内容的提问来源于stack exchange,提问作者James W.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:33:29