Delete images uploaded by ‘Subscriber’ role

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.

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.

Leave a Comment