I've inherited a very poorly designed WordPress site that in part uses BuddyPress for a directory type section. Users are able to upload profile images and 'product' images to their profile.

As a result, we now have roughly 20GB of images on the site and desperately need to cut back on this. When users, stop paying a membership fee to the charity running the site, the users role is changed from one of several custom roles back to the WP 'Subscriber' role.

My hope is that there is a fairly simple and accurate way to find images associated with a user or users profile and then delete these images if the users is has the 'Subscriber' role.

At present I've not tried anything along these lines, and am hoping someone with more WP dev experience might be able to give me some tips / suggestions on how to approach this.

Thanks in advance.

  • 1
    How are the image/user relations stored in the database, do you know? Is it the post author for the attachment in the posts table? Jul 5, 2016 at 11:02

2 Answers 2


Here's some code which pulls all subscriber IDs, then pulls all attachments from those subscribers and attempts to delete them. If it can't delete them it'll write to the error log letting you know.

$subscribers = get_users( array(
    'role'  => 'subscriber',
    'fields'=> 'ID',
) );

if( ! empty( $subscribers ) ) {

    $files = new WP_Query( array(
        'post_type'         => 'attachment',
        'posts_per_page'    => 200,
        'author'            => implode( ',', $subscribers ),
        'fields'            => 'ids',
    ) );

    if( ! empty( $files ) ) {
        foreach( $files->posts as $attachment_id ) {
            $deleted = wp_delete_attachment( $attachment_id, true );

            if( ! $deleted ) {
                error_log( "Attachment {$deleted} Could Not Be Deleted!" );

Odds are you'll have more attachments than your server can handle loading at the same time so you'll probably hit the 200 limit a few times but some page refreshes ( or an actual offset / pagination script ) will do the trick.

  • 1
    That's exactly the sort of thing I was thinking of / hoping for. Thanks for the great answer. Sep 12, 2016 at 8:40

You would need to do a SELECT statement against the wp_posts and wp_users tables to get a list of all file names that qualify. Then manually delete them in the uploads folder. If it's on a Linux server I would create a BASH script to remove them all at once.

  • 1
    Wouldn't this be a really bad way to do it, since it'd be leaving behind all the metadata associated with the images? Additionally, I would imagine this would also result in several thousand blank entries in the WP Media library. Jul 8, 2016 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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