Created
May 11, 2017 09:09
-
-
Save vanbo/797c342b27db201eae1cfcc9fc7768a4 to your computer and use it in GitHub Desktop.
WordPress Media Uploader: Restrict User to Accessing Only Files They Uploaded
This file contains 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
add_filter( 'ajax_query_attachments_args', 'filter_query_attachments_args' ); | |
function filter_query_attachments_args( $query ) { | |
// 1. Only users with access | |
if ( ! current_user_can( 'upload_files' ) ) { | |
wp_send_json_error(); | |
} | |
// 2. No manipulation for admins. | |
// After all they have access to all images. | |
if ( current_user_can( 'administrator' ) ) { | |
return $query; | |
} | |
// 3. No images, if the post_id is not provided | |
if ( ! isset( $_REQUEST['post_id'] ) ) { | |
wp_send_json_error(); | |
} | |
// 4. No images, if you are not the post type manager or author | |
$post = get_post( (int) $_REQUEST['post_id'] ); | |
if ( ! $post instanceof \WP_Post ) { | |
return $query; | |
} | |
// 5. You can also restrict the changes to your custom post type | |
if ( 'listing' != $post->post_type ) { | |
// Only filter for our custom post types | |
return $query; | |
} | |
// 6. Allow only post authors to open the uploader | |
$current_user = wp_get_current_user(); | |
if ( $current_user->ID != $post->post_author ) { | |
wp_send_json_error(); | |
} | |
// 7. Filter to display only images | |
$query['post_mime_type'] = array( | |
'image/gif', | |
'image/jpeg', | |
'image/png', | |
'image/bmp', | |
'image/tiff', | |
'image/x-icon' | |
); | |
// 8. Don't show private images | |
$query['post_status'] = 'inherit'; | |
// 9. Filter to display only the images attached to the post | |
$query['post_parent'] = $post->ID; | |
// 10. Filter to display only the user uploaded image | |
$query['author'] = $current_user->ID; | |
return $query; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment