Skip to content

Instantly share code, notes, and snippets.

@Qubadi
Last active May 16, 2024 09:51
Show Gist options
  • Save Qubadi/07e71872af75d96f8f811306295dafee to your computer and use it in GitHub Desktop.
Save Qubadi/07e71872af75d96f8f811306295dafee to your computer and use it in GitHub Desktop.
Current user media access control in WordPress
UPDATED: 16.05.2024
Description
This PHP snippet enhances the security and organization of the WordPress media library by enforcing user-specific access controls.
It ensures that users can only view, edit, and delete their own uploaded media files, not those uploaded by others.
This functionality is particularly useful in multi-author WordPress environments where maintaining individual user
media privacy is crucial. By integrating this code, administrators can streamline media management and safeguard user
content from unauthorized access.
1. Copy this PHP snippet and paste it into your snippet editor, then save it.
2. Ensure that you have already granted the user access to the media library in WordPress before using this custom code.
_____________________________________________________
// Ensure users only see their own media in the library
if (!function_exists('restrict_media_library')) {
function restrict_media_library($query) {
if (!is_admin()) {
return $query; // Only modify backend requests
}
$user_id = get_current_user_id();
if ($user_id && !current_user_can('administrator')) { // Check if the user is not an admin
$query['author'] = $user_id; // Restrict media items to those uploaded by the current user
}
return $query;
}
add_filter('ajax_query_attachments_args', 'restrict_media_library');
}
// Restrict users from editing or deleting media that isn't theirs
if (!function_exists('restrict_media_edit_delete')) {
function restrict_media_edit_delete($caps, $cap, $user_id, $args) {
if ('edit_post' === $cap || 'delete_post' === $cap) {
$post = get_post($args[0]); // Get the post to check its author
if ($post && $post->post_author != $user_id && !current_user_can('administrator')) { // Check if the user is not the author of the post and not an admin
$caps[] = 'do_not_allow'; // Disallow the capability
}
}
return $caps;
}
add_filter('map_meta_cap', 'restrict_media_edit_delete', 10, 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment