I'm trying to find a way to permanently remove the delete_attachment button from the media details modal. I don't want to use CSS to do it... and haven't been able to find a way as of now. Does anyone have an idea ?


Rather than focusing on the button itself, focus on what you want users to do. If you don't want your users to be able to delete media, and you are also comfortable with them not being able to delete other post types (Posts, Pages, etc.), you can create a custom role for these users.

// In a plugin, add_role will create an entirely new role to assign to users.
add_role('media_editor', 'Media Editor', array(
    // The capabilities below will let these users add, edit, read,
    // but not delete any type of content.
    'create_posts' => true,
    'edit_posts' => true,
    'edit_others_posts' => true,
    'edit_private_posts' => true,
    'edit_published_posts' => true,
    'read_private_posts' => true,
    'read' => true,
    'upload_files' => true
    // You may also wish to add capabilities for other post types,
    // such as create_pages, edit_pages, or custom capabilities
    // for custom post types.

Once this code runs, you can then edit each user and change their role to "Media Editor" (or whatever you decide to call it in your code).

By removing the users' ability to delete any type of posts, they will no longer see the delete button in the media details modal, or any other location. If instead you focus on one button in one modal, you may be leaving other locations - such as the Media Library itself - with buttons they can still use.

| improve this answer | |

I you look at the code that generates this button in media-template.php (currently on lines 488 and 599) you can see that it is pretty much hard coded. So there is no easy way to make sure this button doesn't show up. Hiding it with CSS seems to be the right way.

That would not prevent people from unhiding by fiddling with the CSS, of course. But if someone really means to do harm, he could copy the whole html node from another install and copy it into the DOM of your site on his user side. Then he could still delete the file ... unless you make sure on the server side that the command is not accepted. Ultimately, if you want to prevent people from deleting files, it is not about what code you send to the user end. It's about what is accepted on the server end. That's what you should manage.

A simple option would be to look into wp_delete_attachment. You could use the delete_attachment hook to see if the current user is supposed to do deleting here and kill the page load if he is not. A bit crude, but it works.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy