我用他的能力创建了一个 wordpress 自定义用户:这个用户只能阅读、编辑和删除自定义帖子类型(称为 recipe)的帖子。
我赋予该用户上传文件的角色,因为当用户撰写食谱帖子时,可以将媒体添加到他的文章中。
上传文件在媒体管理器中工作正常(不在媒体 iframe 中,因为编辑附件的条件是具有 edit_post 角色)。
事实上,这个具有自定义角色的用户无法编辑和删除附件(我不能给他 edit_posts 和 delete_posts 角色,因为在这个站点中有很多其他由站点管理员管理的自定义帖子类型
我知道附件是 post_type,但我如何分配编辑和删除他的媒体的功能?
搜索我发现这个黑客可以更改附件的默认功能,但我认为这不是正确的方法
global $wp_post_types;
$wp_post_types['attachment']->cap->edit_post = 'upload_files';
$wp_post_types['attachment']->cap->read_post = 'upload_files';
$wp_post_types['attachment']->cap->delete_post = 'upload_files';
预先感谢
最佳答案
基于@Marco的回答,我想我设法写得更简单:
function allow_attachment_actions( $user_caps, $req_cap, $args ) {
// if no post is connected with capabilities check just return original array
if ( empty($args[2]) )
return $user_caps;
$post = get_post( $args[2] );
if ( 'attachment' == $post->post_type ) {
$user_caps[$req_cap[0]] = true;
return $user_caps;
}
// for any other post type return original capabilities
return $user_caps;
}
add_filter( 'user_has_cap', 'allow_attachment_actions', 10, 3 );
这样,无论其他权限如何,用户都可以对附件进行任何操作。
可以为附件操作定义自定义权限并检查它是否存在以及帖子类型检查。
有关此代码中使用的钩子(Hook)的更多信息 https://codex.wordpress.org/Plugin_API/Filter_Reference/user_has_cap
关于带有upload_files true但edit_post false的Wordpress自定义用户角色,我如何删除和编辑媒体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29566488/