要实现让WordPress的作者(Author)和贡献者(Contributor)无法访问后台个人资料页,并修改用户头像/名称的链接到文章列表,请按照以下步骤操作:
方法一:通过代码实现(添加到主题的functions.php文件)
/**
* 重定向作者和贡献者离开个人资料页
*/
function redirect_author_contributor_from_profile() {
// 检查用户角色和当前页面
if ( is_admin() && ( basename($_SERVER['PHP_SELF']) === 'profile.php' || basename($_SERVER['PHP_SELF']) === 'user-edit.php' ) ) {
$user = wp_get_current_user();
$allowed_roles = array( 'author', 'contributor' );
if ( array_intersect($allowed_roles, $user->roles) ) {
wp_redirect( admin_url('edit.php') ); // 重定向到文章列表
exit;
}
}
}
add_action('admin_init', 'redirect_author_contributor_from_profile');
/**
* 修改顶部管理栏的用户资料链接
*/
function modify_admin_bar_links($wp_admin_bar) {
$user = wp_get_current_user();
$allowed_roles = array( 'author', 'contributor' );
if ( array_intersect($allowed_roles, $user->roles) ) {
// 修改主用户名链接
$wp_admin_bar->add_node(array(
'id' => 'my-account',
'href' => admin_url('edit.php?author=' . get_current_user_id())
));
// 移除"编辑个人资料"子菜单
$wp_admin_bar->remove_node('edit-profile');
}
}
add_action('admin_bar_menu', 'modify_admin_bar_links', 999);
/**
* 修改前端作者存档链接(可选)
*/
function modify_author_archive_link($link, $author_id, $author_nicename) {
$user = get_user_by('id', $author_id);
if ( in_array('author', $user->roles) || in_array('contributor', $user->roles) ) {
return admin_url('edit.php?author=' . $author_id); // 指向后台文章列表
}
return $link;
}
add_filter('author_link', 'modify_author_archive_link', 10, 3);
方法二:通过插件实现
- 安装插件:使用 “User Role Editor” 或 “Members” 插件调整用户权限。
- 移除权限:在插件设置中移除作者/贡献者对
edit_users和edit_user_profile的能力。 - 菜单编辑器:使用 “Admin Menu Editor” 插件隐藏后台的个人资料菜单项。
效果说明
- 后台限制:作者/贡献者访问
profile.php或user-edit.php时会自动跳转到文章管理界面。 - 顶部导航栏:点击用户名会直接进入用户的文章列表(而非资料页)。
- 前端作者链接(可选):文章页面的作者链接也会指向后台文章列表。
注意事项
- 代码放置:建议通过子主题添加代码,避免主题更新丢失修改。
- 权限验证:确保不要影响管理员/编辑角色的正常使用。
- 安全备份:修改前建议备份网站文件和数据库。
如果遇到问题,可以通过插件方式实现更安全的权限控制!