Skip to content

Instantly share code, notes, and snippets.

@nacin
Created October 12, 2011 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nacin/1279980 to your computer and use it in GitHub Desktop.
Save nacin/1279980 to your computer and use it in GitHub Desktop.
Blocking Attachments from Editing/Deletion
<?php
// Plugin Name: Blocking Attachments from Editing/Deletion
/*
* The map_meta_cap_ filter runs on a meta capability, such as edit_post and delete_post.
* When these caps are caught by WordPress, it converts this to the required caps. For example,
* the edit_post meta capability, checked against a published post, requires the edit_published_posts
* capability. If the user isn't the same as the author, it also requires the edit_others_posts
* capability.
*
* add_filter() takes four arguments: The filter, the callback function, priority (default 10),
* and the number of arguments we want (default 1).
*/
add_filter( 'map_meta_cap', 'block_attachments_from_edit_delete', 10, 4 );
/*
* This callback function takes four arguments. The final capabilities (an array, $caps) required
* for the meta cap requested, which is the second argument (a string, $cap). Then the user
* ID, typically the current user. Finally, an array of arguments that were originally passed
* to the current_user_can() function. For example, current_user_can( 'edit_post', $post_id ). In
* this situation, $post_id would be $arg[0].
*/
function block_attachments_from_edit_delete( $caps, $cap, $user_id, $args ) {
// If the meta capability is either delete_post, or edit_post, continue:
if ( $cap == 'delete_post' || $cap == 'edit_post' ) {
// $arg[0] is the post ID. Let's pull up that post object.
$post_id = $args[0];
$post = get_post( $post_id );
// If we're dealing with an attachment, we want to restrict this to Editors.
// In that case, we can simply require that the meta cap check an additional
// capabiltiy -- 'edit_others_posts' or 'delete_others_posts'. Only Editors
// and Admins have this cap.
if ( $post->post_type == 'attachment' ) {
if ( $cap == 'delete_post' )
$caps[] = 'delete_others_posts';
else
$caps[] = 'edit_others_posts';
}
// If we're dealing with a post that is published, then require either
// delete_others_posts or edit_others_posts.
elseif ( $post->post_type == 'post' && $post->post_status == 'publish' ) {
if ( $cap == 'delete_post' )
$caps[] = 'delete_others_posts';
else
$caps[] = 'edit_others_posts';
}
}
// Important for filters. Return the data.
return $caps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment