Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress custom user roles with upload_files true but edit_post false, how can i delete and edit media?

I created a wordpress custom user with his capabilities: this user can only read, edit and delete posts of a custom post type ( called recipe ).

I give to this user the role to upload file, because when user write a recipe post can add media to his article.

Upload file work fine in media manager ( not in media iframe, because the conditions in order to edit attachments is have the edit_post role ). In fact, this user with custom roles cannot edit and delete attachments ( i cannot give him the edit_posts and delete_posts roles because in this site there are a lot of other custom post type managed by site administrator

I know that attachment are post post_type, but how can i assign the capabilities to edit and delete his media?

Searching i found this hack to change default capabilities of attachments, but i don't think it's the right way

 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';

Thank in advance

like image 836
Marco Avatar asked Apr 10 '15 16:04

Marco


1 Answers

Based on @Marco answer I think I manage to write it simpler:

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 );

This way regardless of other permissions users can do everything with attachments.

One may define custom permissions for attachments actions and check if it exists along with post type check.

More info about hook used in this code https://codex.wordpress.org/Plugin_API/Filter_Reference/user_has_cap

like image 94
jmarceli Avatar answered Sep 19 '22 18:09

jmarceli