disable delete media wordpress

Here’s what I’ve been trying to figure out how to do for hours now.

I want the author role to be able to upload content into the media library from their posts, and to be able to view the entire media library. What I don’t want is to let the author role delete any media, even their own.

Read More

I’ve thought about automatically switching authors to a ‘media’ user upon upload completion, but I was hoping there’d be a cleaner way.

Any ideas?

Related posts

Leave a Reply

3 comments

  1. There’s no built-in capability for “delete_media.” I think this is encompassed by “delete_posts,” since uploads are treated as posts. (Note that authors can delete only their own posts and attachments.)

    Adding a role or capability is possible, but you’d have to replace the default media admin screens, where the delete action is controlled by the “delete_posts” cap. You don’t want to mess with the core files upload.php etc. So you’d have to restrict access to them, then write your own panels for authors. You probably don’t want to do this. 🙂

    There’s a better way, however. If you assign uploads to an administrator when they are saved then authors will not be able to delete them. You can use the add_attachment and edit_attachment action hooks to change the post_author to an administrator id.

    Hope that helps.

  2. There are a number of places where WordPress will let users delete images, so trying to hide them all can be challenging (and dangerous, because a new plug-in or version of WordPress could add another). However, you can add the following function to prevent deletions and throw an error (not pretty, but effective). You could enhance this by adding a custom capability for deleting images, if you wanted a finer level of control.

    add_action('delete_attachment', 'DontDeleteMedia', 11, 1);
    function DontDeleteMedia($postID)
    {
        if (!current_user_can('manage_options')) {
            exit('You cannot delete media.');
        }
    }
    
  3. add this code in your functions.php file:

    add_action('media_row_actions','users_own_attachments', 2, 1);
    function users_own_attachments( $wp_query_obj ) {
        if( !current_user_can( 'delete_plugins' ) ){
            unset($wp_query_obj['delete']);
            return $wp_query_obj;
        }
    }