本文介绍如何通过自定义用户能力(capability)与 `user_has_cap` 钩子,实现 wordpress 中“用户仅能编辑自己上传的媒体文件”的精细化权限控制,弥补原生 `upload_files` 能力过度开放的缺陷。
在 WordPres
s 默认权限体系中,upload_files 是一个全局性能力——一旦赋予某角色该能力,该角色用户即可访问并编辑所有媒体库中的文件(包括他人上传的内容),这在多作者、投稿型或客户协作类站点中存在明显安全隐患。WordPress 并未提供原生的 edit_own_files 或类似细粒度能力,因此需通过扩展权限逻辑来实现精准控制。
// 1. 注册自定义能力(仅需运行一次,例如激活插件时)
function my_register_edit_own_files_capability() {
$editor_role = get_role('editor'); // 可替换为自定义角色,如 'contributor' 或 'client'
if ($editor_role) {
$editor_role->add_cap('edit_own_files');
}
}
// add_action('init', 'my_register_edit_own_files_capability'); // 激活时启用,之后注释掉
// 2. 动态校验编辑权限
add_filter('user_has_cap', 'restrict_attachment_editing_to_owner', 10, 4);
function restrict_attachment_editing_to_owner($allcaps, $caps, $args, $user) {
// 仅处理附件编辑相关操作:edit_post, edit_attachment, delete_post 等
$target_cap = $args[0];
$post_id = isset($args[2]) ? (int) $args[2] : 0;
if (!in_array($target_cap, ['edit_post', 'edit_attachment', 'delete_post', 'delete_attachment']) || !$post_id) {
return $allcaps;
}
$post = get_post($post_id);
if (!$post || 'attachment' !== $post->post_type) {
return $allcaps;
}
// 若当前用户是附件作者,且拥有 edit_own_files 能力,则允许操作
if ($post->post_author == $user->ID && user_can($user, 'edit_own_files')) {
$allcaps[$target_cap] = true;
} else {
// 显式拒绝:防止其他能力(如 upload_files)越权覆盖
$allcaps[$target_cap] = false;
}
return $allcaps;
}通过组合自定义能力与 user_has_cap 钩子,开发者可完全接管 WordPress 的附件编辑权限判定流程,实现真正以用户为中心的资源隔离。该方案轻量、可复用,且不依赖第三方插件,是构建高安全性多用户 WordPress 站点的核心实践之一。