Skip to content

Instantly share code, notes, and snippets.

@EarthmanWeb
Last active January 4, 2024 21:29
Show Gist options
  • Save EarthmanWeb/f2918d9b3cb7933b75a63bf9b5c217f3 to your computer and use it in GitHub Desktop.
Save EarthmanWeb/f2918d9b3cb7933b75a63bf9b5c217f3 to your computer and use it in GitHub Desktop.
Custom WP caps for media library
function em_setup_media_permissions() {
add_filter( 'user_has_cap', 'em_grant_media_permissions_except_subscriber', 1000, 4 );
}
// add custom caps to enable media permissions for custom roles
function em_grant_media_permissions_except_subscriber( $allcaps, $caps, $args, $user ) {
$post_id = isset( $_REQUEST['post'] ) ? $_REQUEST['post'] : ( isset( $args[2] ) ? $args[2] : null );
if ( ! $post_id ) {
return $allcaps;
}
// Check if the user has a role in a array or roles
$allowed_roles = array(
'news_editor',
'events_editor',
);
// now check if the user has any of the above roles
if ( array_intersect( $allowed_roles, $user->roles ) ) {
// Check if we're dealing with a specific post (like a media attachment)
$post_id = isset( $_REQUEST['post'] ) ? $_REQUEST['post'] : ( isset( $args[2] ) ? $args[2] : null );
if ( $post_id ) {
$post = get_post( $post_id );
// Check if it's an attachment and the capability being checked is related to post management
if ( $post && $post->post_type == 'attachment' ) {
// Grant capabilities to edit, delete, and upload files
$capabilities = array(
'manage_posts',
'create_posts',
'edit_post',
'edit_others_posts',
'edit_posts',
'delete_posts',
'delete_others_posts',
'publish_posts',
'publish_others_posts',
'edit_others_posts',
'edit_files',
'upload_files',
);
$allcaps += array_fill_keys( $capabilities, 1 );
return $allcaps;
}
}
}
return $allcaps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment