Delete images uploaded by ‘Subscriber’ role

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