Home > Dev > WordPress Optimization > Automatically Deleting Unused Images

Automatically Deleting Unused Images

This code will delete unused images from the uploads directory.

// Add this to your theme's functions.php file

function delete_unused_images() {
    global $wpdb;
    $upload_dir = wp_get_upload_dir();
    $images = glob($upload_dir['basedir'] . '/**/*.{jpg,jpeg,png,gif}', GLOB_BRACE);
    
    foreach ($images as $image) {
        $attachment_id = attachment_url_to_postid($image);
        if (!$attachment_id) {
            unlink($image);
        }
    }
}

if (!wp_next_scheduled('delete_unused_images')) {
    wp_schedule_event(time(), 'weekly', 'delete_unused_images');
}

add_action('delete_unused_images', 'delete_unused_images');
Back