使用upload_files的Wordpress自定义用户角色为true但edit_post为false,如何删除和编辑媒体?

Mar*_*rco 5 media wordpress user-roles

我创建了一个具有其功能的wordpress自定义用户:此用户只能读取,编辑和删除自定义帖子类型(称为配方)的帖子.

我给这个用户上传文件的角色,因为当用户写一篇食谱帖子时可以在他的文章中添加媒体.

上传文件在媒体管理器中工作正常(不在媒体iframe中,因为编辑附件的条件具有edit_post角色).事实上,这个具有自定义角色的用户无法编辑和删除附件(我不能给他edit_posts和delete_posts角色,因为在这个站点中有很多其他自定义帖子类型由站点管理员管理

我知道附件是post 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';
Run Code Online (Sandbox Code Playgroud)

预先感谢

Mar*_*rco 5

搜索后,我找到了我的问题的答案:为了允许没有 edit_post=true 的用户,只有当 post_type 是带有过滤器 user_has_cap 的附件时,我们才能将其设置为 true。为了我的目的,我写了这个钩子

add_filter( 'user_has_cap', 'myUserHasCap', 10, 3 );

function myUserHasCap( $user_caps, $req_cap, $args ) {

$post = get_post( $args[2] );

if ( 'attachment' != $post->post_type )
    return $user_caps;

if ( 'delete_post' == $args[0] ) {

    if ( $user_caps['delete_others_posts'] )
        return $user_caps;

    if ( !isset( $user_caps['publish_recipes'] ) or !$user_caps['publish_recipes'] )
        return $user_caps;

    $user_caps[$req_cap[0]] = true;

}

if ( 'edit_post' == $args[0] ) {

    if ( $user_caps['edit_others_posts'] )
        return $user_caps;

    if ( !isset( $user_caps['publish_recipes'] ) or !$user_caps['publish_recipes'] )
        return $user_caps;

    $user_caps[$req_cap[0]] = true;

}

return $user_caps;

}
Run Code Online (Sandbox Code Playgroud)

我希望对正在寻找我问题答案的其他人有用。


jma*_*eli 5

基于@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 );
Run Code Online (Sandbox Code Playgroud)

这样,无论其他权限如何,用户都可以使用附件执行所有操作.

可以为附件操作定义自定义权限,并检查它是否与帖子类型检查一起存在.

有关此代码中使用的钩子的更多信息,请访问https://codex.wordpress.org/Plugin_API/Filter_Reference/user_has_cap