0

I am trying to write a function to upload and delete images on frontend with dropzonejs uploader, and so far i managed to make everything work.

But the problem is that i need to secure it that the image that is deleting is actually uploaded by the user who is deleting image.

In wordpress admin area in media library when i click on image, in attachments details there is a Uploaded by with username who uploaded specific image.

But on searching all over the net and wordpress codex i didn't find any info how to retrieve user id who uploaded the image.

So id i have image id and try to delete with wp_delete_attachment is there a way to check who is the uploader of that image and compare logged in user id with image uploader id and if those two match delete the image.

0

I am using something similar in my website, to only show media attachements uploaded by other users, if this is an option for you, you can use the code or you can edit it to match your need but the truth is that it gets the user ID in the same way it would get it from a post with post_author

Here's the code you can test it and see if this will work good for you.

//Hide Media Library images Start
function hide_posts_media_by_other($query) {
    global $pagenow;
    if (( 'edit.php' != $pagenow && 'upload.php' != $pagenow ) || !$query->is_admin) {
        return $query;
    }
    if (!current_user_can('manage_options')) {
        global $user_ID;
        $query->set('author', $user_ID);
    }
    return $query;
}

add_filter('pre_get_posts', 'hide_posts_media_by_other');

add_filter('posts_where', 'hide_attachments_wpquery_where');

function hide_attachments_wpquery_where($where) {
    global $current_user;
    if (!current_user_can('manage_options')) {
        if (is_user_logged_in()) {
            if (isset($_POST['action'])) {
                if ($_POST['action'] == 'query-attachments') {
                    $where .= ' AND post_author=' . $current_user->data->ID;
                }
            }
        }
    }
    return $where;
}

//Hide Media Library images END
0

The solution is actually very simple, it's just one line of code, since i realized that attachment id is actually same as any other post id i can retrieve user id based on post field.

$post_author_id = get_post_field( 'post_author', $post_id );

This gets the user id of the user who uploaded image and $post_id is image attachment id

So further checking

if( $post_author_id == $current_user->ID )

Checks if the uploader of the image and currently loged in user are the same and allow or cancel image deletion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.