Last active
November 3, 2024 12:17
-
-
Save Qubadi/07e71872af75d96f8f811306295dafee to your computer and use it in GitHub Desktop.
Current user media access control in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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